CS代考 COSC 407: Introduction to Parallel Computing

Intro to Parallel Computing
Topic 2 – Intro to C
COSC 407: Introduction to Parallel Computing
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
– IntrotoC,
– Preprocessors,CompilingCprograms
– JavavsC,Datatypes,variables,Operators
– Functions
– Pointers(memoryallocation,2Darrays,functions)
§ Next Lecture:
– MorePointers(memoryallocation,2Darrays,functions) – ErrorHandling
– Stringprocessing
– struct,typedef
– Preprocessors,CompilingCprograms
Topic 2: Intro to C COSC 407: Intro to Parallel Computing

Poll – I C….
§ How do you feel about C (are you c-faring)? A. I am already fluent with C
B. IamokwithwithC
C. I don’t know much about C
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
Objectives
§ Getting started § Intro to C
– This is not an “Intro to C programming” course
• Will cover some of the challenging concepts • You must know the basics of writing C code – Parallel programming will be done in C
– You will reuse what you already know (Java/Python/something else…).
• Not start from scratch
§ Pointing out where to find information § Pointing out common mistakes
Topic 2: Intro to C COSC 407: Intro to Parallel Computing

C & the Impact of
A “simple” procedural programming language developed by while at Bell Labs in the 1970’s
“…without Dennis there would be no C programming language. Without C there would be no C++. That means there won’t be any Windows, Unix, Linux, Firefox, Photoshop, After Effects, Fl Studio, VLC Media Player, Microsoft Words, Excel. It also means no PC Games, Xbox Games, Playstation Games. No Black Ops, Halo, Warcraft, Grand Theft Auto. The list is endless. 90% of computer applications in the world are written in C and C++.
Without UNIX, there would be no internet. That means no Google, Facebook, Youtube,
Wikipedia, etc.
Apple, Microsoft, and most other computer companies would be nothing without him.”
Source: http://www.likeyou.me/index.php/tech/steve-jobs-vs-dennis-ritchie/994/
(b. September 9, 1941; d.October 12, 2012)
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
§ There are many books and tutorials available,
– TheCProgramminglanguage,B.W.Kernighanand , Prentice-Hall (K&R C)
– CProgramming:amodernapproach,K.N.King, http://knking.com/books/c/
– Manyonlinetutorials
• http://www.tutorialspoint.com/cprogramming
• http://www.cprogramming.com/tutorial/c-tutorial.html
§ IDEs and compilers
– GCC(GNUCompilerCollection)
– EclipseforIDEforC/C++Developers – SomeonlineIDEsandcompilers
• https://www.onlinegdb.com/online_c_compiler • https://replit.com/languages/c
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
COSC 211 S2020 Term 1 – UBCO –

§ The Labs are equipped with the required software § If you use your laptop, the following list is required
– Aneditor
• Eclipse for Scientific Computing
• or your preferred IDE
• or you can even use command line + an editor of some sort
– C compiler
• Windows – MinGW (Minimalist GNU for Windows)
– http://www.mingw.org – Requires configuration
» See Canvas for instructions. • macOS – Apple command line tools • Linux–J
– Moresoftwarewillbeneededasweproceed,butnot today…
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing
§ Paradigm: C is not object-oriented. Methods are called functions and procedures (but C++ is OO)
§ Program organization: A program in C contains a collection of source and header files. The header contains function protocols and should be included if you want to use a specific function defined in that module.
– Smallandefficientlibraries
§ Memory Management: C does not have the garbage-
§ Performance: C is faster than Java
§ Lower-level language is needed to get closer to the hardware
§ Java hides many details
– Memorymanagement
– Initializations
– Buffermanagement,arraybounds
collection mechanism
Topic 2: Intro to C COSC 407: Intro to Parallel Computing

§ Simple procedural language for programming Operating Systems
§ Direct access to memory
§ Small library
§ Efficient execution
§ Reasonably portable
– more than Assembly Language
– At the source code level
§ Encouraged Structured Programming
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
What Does That Mean?
§ Speed, speed, speed
§ Programmer knows what (s)he is doing, do it as fast
as possible
§ Error checking is for weak of heart….
– no exception handling
– no error bound checks on arrays
– plenty of opportunities for buffer overflows
§ With great power, comes great responsibility – Tread carefully!!
Topic 2: Intro to C COSC 407: Intro to Parallel Computing

C vs. Java
§ The basic syntax of C is similar to Java.
– Keywordsint,if,for,while,…etc.
§ Some differences:
– Cisnotobject-oriented.
• Basic programming unit is “function” (“method” in Java), not “class”.
– Cis‘fairly’stronglytyped
• Allows implicit conversion between types • But original variable type does not change
– Cprogramsarenotportableattheexecutablefileslevel • Source code should be re-compiled to run on new
– Cdoesnothavethegarbagecollectionmechanism
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
C vs. Java
§ A source program in C uses header files
– A header file has an extension .h and contains
function declarations
• for .h files that the programmer writes:
#include “file”
• for .h files that come with your compiler: #include
§ Some more differences:
– structs, pointers, arrays, and some more things….
Topic 2: Intro to C COSC 407: Intro to Parallel Computing

Elements of a C Program
§ A C development environment includes:
– System libraries and headers: a set of standard libraries and their header files. Example: stdio.h
– Application Source: application source and header files
– Compiler: converts source to object code for a specific platform
– Linker: resolves external references and produces the executable module
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
Source and Header files
§ Header files (*.h) contain external interface definitions such as function prototypes, data types, macros, inline functions and other common declarations.
§ Do not place source code in the header file with a few exceptions (const and struct definitions).
§ The C preprocessor is used to insert common definitions into source files. The include preprocessor directive is used to tell the compiler that you want to include code from another place.
– Includes are typically used to specify files used by your program containing class declarations.
– More later….
Topic 2: Intro to C COSC 407: Intro to Parallel Computing

C Compilation
Preprocessor executes commands in code beginning with #.
Compiler translates source code into object (machine) code. Checks for syntax errors and warnings.
Compiler translates source code into object (machine) code but
not functions from header files. Checks for syntax errors and warnings.
Linker replaces missing object files with appropriate code (links things together)
Topic 2: Intro to C
Source File pgm.c Preprocessor
Modified Source Code
Program Object Code File pgm.o
Executable File a.out
COSC 407: Intro to Parallel Computing
C vs Java Example
“Hello World” program!
import java.lang.* //not necessary public class HelloWorld {
public static void main(String[] args){ System.out.println(“Hello UBC”);
include stdio. header to compile the printf command
main is the first procedure to be executed
#include
int main(void){
printf(“Hello UBC\n”);
return 0; }
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing
COSC 211 S2020 Term 1 – UBCO –

Example, cont’d
#include
#include
int main(void){ printf(“Hello World\n”); return EXIT_SUCCESS;
Topic 2: Intro to C
include stdlib.h to use EXIT_SUCCESS
A constant = 0 that indicates successful execution (same as “return 0;”)
This constant is declared in stdlib.h as a macro. Macros are discussed later
COSC 407: Intro to Parallel Computing
Data Types – Integer
§ Integer types (can be signed (default) or unsinged)
Storage size (machine dependent)
-128 to 127
2 or 4 bytes
-32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
0 to 65,535 or
0 to 4,294,967,295
-32,768 to 32,767
0 to 65,535
-2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
• To use unsigned types, put the keyword ‘unsigned’ before the type.
• size depends on particular system
– Use sizeof(type) to find the value on your platform
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing

Data Types Floating-point/void
§ Floating-point types
§ void Represents the absence of type.
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
Storage size
1.2E-38 to 3.4E+38
6 decimal places
2.3E-308 to 1.7E+308
15 decimal places
long double
3.4E-4932 to 1.1E+4932
19 decimal places
§ A variable is a name given to a memory storage location that we can manipulate in our programs.
– Avariablenamecanonlyhaveletters(bothuppercaseand lowercase letters), digits and underscore.
– Thefirstletterofavariableshouldbeeitheraletteroran underscore.
– Thereisnoruleonhowlongavariablename(identifier)can be. However, you may run into problems in some compilers if the variable name is longer than 31 characters.
§ Global variables:
Includeallvariablesdeclaredoutsideanyfunction(and outside main too).
:0fornumbers,‘\0’forchar,NULLfor pointers
• Still just initialize them
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing

§ Local variables:
– Includeallvariablesdeclaredinsideafunction
– Canbeusedonlywithinthefunctionthatdeclaresthem
– Nodefaultvaluebythesystem–youneedtoinitialize them.
§ A program may have a local and global variable with the same name, but inside a function the local variable will take preference.
§ Constants: create a constant by adding the keyword const before the declaration.
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
Type Conversion
int i, j = 0; float y; floatx=y=1.4; i = (int) x;
y = x + (int) i;
x = y + j;
char z = i;
// j is initialized, but i is not!
//yisdeclaredbefore.Bothxandy=1.4 // i = 1
// implicit conversion: y = 1.0;
// y = 1.4 + 1 = 2.4
// x = 2.4 + 0 = 2.4
// z = 1. implicit conversión int -> char
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing

C Syntax is Similar to Java
while (money > 0) { money–;
drink another beer();
do { sleep++;
}while(sleep<10); for int i; //declared outside if not C99 mode for (i = 1; i <= 10; i++) { printf("%d squared is %d\n", i, i*i); COSC 407: Intro to Parallel Computing /* block comment */ // in line comment if (pi == 3){ location="india"; location = "unknown"; location = (pi == 3 ? "india" : "unknown"); Topic 2: Intro to C C Syntax is Similar to Java c = getchar(); switch (c) { case 'Q': case 'q': //read a single character //terminate the calling process immediately. //Part of stdlib.h printf("valid inputs and 'q', 'c' and 'd'\n"); Topic 2: Intro to C COSC 407: Intro to Parallel Computing Output Using printf printf("Number: %d", n); printf("%s: %d","Number", n); § printf writes to stdout a stream of characters. § printf takes a quoted string which may contain both text and variable place holders. Variables appear in a comma-separated list at end of the function call in order. Variable placeholders: – %d –%u –%f – %s – %c Topic 2: Intro to C or %i - signed decimal number - unsigned decimal number - floating-point number - character string (null-terminated) - single character COSC 407: Intro to Parallel Computing Input Using scanf int n; scanf("%d", &n); scanf reads a value entered by the user. • It uses the same type placeholders as printf. • Make sure to use an & as a pointer is being passed in. Note: It is possible to read multiple values in one scanf: scanf("%d%f", &n, &f); Topic 2: Intro to C COSC 407: Intro to Parallel Computing COSC 211 S2020 Term 1 – UBCO – COSC 211 S2020 Term 1 – UBCO – printf / scanf #include
int main(){
printf(“Enter two numbers: ” );
scanf(“%d %d”, &n1,&n2 );
printf(“The sum of %d and %d is %d\n”, n1, n2, (n1+n2) ); return 0;
Enter two numbers: 3 7
The sum of 3 and 7 is 10
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing
§ On some systems, you need to put fflush(stdout) right after your print statement printf(). Why?
Onthesesystems,dataonthestdoutremainbufferedand wait until we print enough stuff (to fill the buffer), we explicitly flush the buffer, or the program terminates.
Thisisforefficiencyreasons(bufferedoutputisgenerally much more efficient)
#include
int main(){
printf(“Enter two numbers: ” );
fflsuh(stdout);
scanf(“%d %d”, &n1,&n2 );
printf(“The sum of %d and %d is %d\n”, n1, n2, (n1+n2) ); return 0;
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing

More Input / Output functions
§ Reading/writing a single character char c = getchar();
putchar(c);
§ Reading a string
char str[20];
fgets(str, 20, stdin); //or gets(str) or scanf(“%s”, str);
– fgets reads a line from the stdin and stores it into the string pointed to by str. The input is stopped when reading 19 characters or when Enter is pressed.
• gets(str) provides no protection against overflow
§ Writing a string to standard output puts(“hello”);
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing
§ Most operators are the same as Java. – Arithmetic+,-,*,/,%
– Relational>=,<=,==,!=,>,< – Logic&&,||,! • 0 is considered false and non-zero values are true – Assignment:=,+=,-=,*=,/=,%=,|=,etc. – Increment/decrement:++,-- § Bitwise operators (working on data bit-by-bit): Shift Left Shift Right NOT & bitwise AND | bitwise OR ^ bitwise XOR Topic 2: Intro to C COSC 407: Intro to Parallel Computing Find the Error... 1) Spot the error: int x = 0; while (x < 10); { printf("x=%d\n", x); 2) Spot the error: printf("x = %d, y = %d\n", x); Topic 2: Intro to C COSC 407: Intro to Parallel Computing An array is a collection of data items of the same type. Static array definition: int myArray[10]; // Integer array of size 10 const int ARRAY_SIZE = 50; double values[ARRAY_SIZE]; Accessing an element of an array is performed using the open and closed square brackets “[]”: Topic 2: Intro to C const int ARRAY_SIZE = 50; double values[ARRAY_SIZE]; for (i=0; i < ARRAY_SIZE; i++) printf("%d\n",values[i]); COSC 211 S2020 Term 1 – UBCO – ScottCOSC 407: Intro to Parallel Computing Fazackerley § Declaring, initializing, and accessing arrays: a[0] = 10; a[1] = 20; int b[2] = {3, 2}; int c[] = {5, 9, -2}; int d[2][3] = {{5, 9, -2}, {1, -3, 2}}; //or int d[][3] for(i = 0; i < 5; i++) //prints 10,20 printf("%d\n", a[i]); //declare int array of 2 elements //declare and initialize //declare and initialize //and 3 more values!! Topic 2: Intro to C COSC 407: Intro to Parallel Computing Length of the array using sizeof operator § sizeof returns the number of bytes taken by a variable int n = sizeof(a)/sizeof(a[0]); //n = number of elements in a § sizeof CANNOT find the size of an array in the following cases: – If the array is created using malloc – If the array is received as a function argument In both cases, the array is treated as a pointer, so sizeof will return the pointer's size, not the array's size Topic 2: Intro to C COSC 407: Intro to Parallel Computing Functions have prototypes that must be declared before referenced. A prototype is the declaration line without the function body. • declaration of the function name, return type, and parameters. Function definition provides the actual body of the function § C is call by value meaning that a copy of the parameter is passed to the function. § Many built-in functions that are provided in the C libraries: e.g., strcat() Topic 2: Intro to C COSC 407: Intro to Parallel Computing Function definition before the main function Topic 2: Intro to C COSC 407: Intro to Parallel Computing Passing an Array to a Function Topic 2: Intro to C COSC 407: Intro to Parallel Computing Declaring Pointer Variables A pointer variable stores an address to a particular location in memory. Pointers point to an object of a particular data type. – A pointer variable is declared by putting a "*" in front of the variable name: variableType *variableName; § For example: int *intPtr; double *d; char *strPtr; All pointer variables store an address not the actual type. – The type is important to know how many consecutive bytes to retrieve starting at the given address. Topic 2: Intro to C COSC 407: Intro to Parallel Computing COSC 211 S2020 Term 1 – UBCO – § Each memory location has an address. A variable address can be accessed using the & operator § Example: Print the address of a variable x #include
int main(void) {
int z = 7;
printf(“Address of z: %p\n”, &z);
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
Manipulating Pointers
§ The value of a pointer variable can be changed like any other variable using assignment. Example:
int *intPtr, *intPtr2, i = 1;
intPtr = &i;
intPtr2 = intPtr;
§ Memory diagram: intPtr
// intPtr stores address of i
// intPtr2=intPtr1 (address of i)
– Note that the ampersand “&” denotes the address of a variable. (address operator)
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing

NULL Pointer Values
If you do not want a pointer to point to anything, you set its value to NULL. Example:
int *intPtr, *intPtr2, i = 1;
intPtr = &i;
intPtr2 = NULL;
Memory diagram:
! The value of NULL is 0. Topic 2: Intro to C
// intPtr stores address of i
// intPtr2=NULL (points to nothing)
COSC 407: Intro to Parallel Computing
De-referencing a Pointer Variable
To change the value of a variable when you have its pointer (address), you must de-reference the address to operate on the data, not the pointer itself.
To deference a pointer variable, put a “*” in front of the pointer (think ‘value at’.
– This means that you are interested in the value pointed to, not the value of the address pointer.
Topic 2: Intro to C COSC 407: Intro to Parallel Computing
COSC 211 S2020 Term 1 – UBCO –
COSC 211 S2020 Term 1 – UBCO –

De-referencing a Pointer Variable
Example 1:
int *intPtr, j = 5; intPtr = &j;
*intPtr = 8;
Memory diagram:
// Correct – changes value
COSC 407: Intro to Parallel Computing
Topic 2: Intro to C
Forgetting to De-reference
Example 2:
int *intPtr, j = 5; intPtr = &j;
intPtr = 8;
Memory diagram:
// Incorrect – changes address
Topic 2: Intro to C
COSC 407: Intro to Parallel Computing
COSC 211 S2020 Term 1 – UBCO –
COSC 211 S2020 Term 1 – UBCO –

Pointers, cont’d
§ Remember these two operators: – Value at address (*):
• gives the value stored at a particular address • *p is y in the example in the previous slide
– This is called “dereferencing” p
– Address of (&):
• gives address of a variable
– Also called ‘indirection operator’