csse221: software dev. honors day 26 announcements announcements simulation project due tomorrow...
Post on 20-Dec-2015
219 views
TRANSCRIPT
CSSE221: Software Dev. Honors CSSE221: Software Dev. Honors Day 26Day 26
AnnouncementsAnnouncements Simulation Project due tomorrow Simulation Project due tomorrow
nightnight Details of what should go into Details of what should go into
Executive Summary are postedExecutive Summary are posted Final Partner Accountability Survey is Final Partner Accountability Survey is
postedposted Hopefully, you checked C Hopefully, you checked C
installation in Eclipse by now, and installation in Eclipse by now, and written “Hello World”.written “Hello World”.
This week: Intro to CThis week: Intro to C
Monday:Monday: Project dayProject day
Tuesday:Tuesday: Introduction to CIntroduction to C
Similarities to JavaSimilarities to Java Lots of little differencesLots of little differences structsstructs filesfiles
Thursday:Thursday: Pointers and dynamic memory Pointers and dynamic memory
allocation in Callocation in C
Why learn C?Why learn C? Intrinsic benefitIntrinsic benefit
Low-level control of hardware and operating systemLow-level control of hardware and operating system CPEs and EEs tend to use oftenCPEs and EEs tend to use often
Fast!Fast! Opens doors in futureOpens doors in future
Graphics (OpenGL library), Fractals, Operating Systems, Graphics (OpenGL library), Fractals, Operating Systems, and Networks coursesand Networks courses
Lots of employers like C/C++Lots of employers like C/C++ Helps differentiate programming concepts from Helps differentiate programming concepts from
languagelanguage
But power at a price:But power at a price: No garbage collection: need to do your own memory No garbage collection: need to do your own memory
managementmanagement Can overwrite memoryCan overwrite memory More room for mistakesMore room for mistakes
Some will love it, others won’t.Some will love it, others won’t. Ready?Ready?
My First C ProgramMy First C ProgramCCJavaJava
SimilaritiesSimilarities Same operators:
Arithmetic int i = i+1; i++; i--;
i *= 2; +, -, *, /, %,
Relational and Logical <, >, <=, >=, ==, != &&, ||, &, |, !
Many identical types: int, short, long, float,
double
Same control syntax: if ( ) { } else { } while ( ) { } do { } while ( ); for(i=1; i <= 100;
i++) { } switch ( ) {case 1:
… } continue; break;
More SimilaritiesMore Similarities
JavaJava MethodsMethods I/O: printlnI/O: println importimport
java.lang.Arraysjava.lang.Arrays arraysarrays
2D arrays2D arrays static final static final
MAX_LEN = 10;MAX_LEN = 10;
CC FunctionsFunctions printfprintf #include <stdio.h>#include <stdio.h> arrays (but arrays (but
constantconstant size) size)
same: same: int points[3][4];int points[3][4];
#define MAX_LEN #define MAX_LEN 1010
Major differencesMajor differences
I/O (printf, scanf) uses format strings I/O (printf, scanf) uses format strings C has structs, not classes.C has structs, not classes.
Can hold data but no methodsCan hold data but no methods No classes means no String class.No classes means no String class.
A string is just an array of charactersA string is just an array of characters Tricky-to-use string functions.Tricky-to-use string functions.
Reference variables are explicit: called Reference variables are explicit: called pointerspointers.. Can be used even for primitivesCan be used even for primitives
Formatted printingFormatted printing
char name[] = "Bob";char name[] = "Bob";
int x = 17;int x = 17;
printf("Hello there, %s. Your favorite " printf("Hello there, %s. Your favorite " " number is %d and its square root is " " number is %d and its square root is " "%4.2f\n", name, x, sqrt(x));"%4.2f\n", name, x, sqrt(x));
printf("Hello there, %s.\n\tYour " printf("Hello there, %s.\n\tYour " "\"favorite\" number is %d and its square " "\"favorite\" number is %d and its square " "root is %4.2f\n", name, x, sqrt(x));"root is %4.2f\n", name, x, sqrt(x));
printf – printf – frequently used frequently used conversion codesconversion codes
codcodee
data typedata type ExampleExample
dd decimaldecimal(int, long)(int, long)
int x=4, y=5;int x=4, y=5;printf("nums %3d, %d%d\n", x, y, x+y");printf("nums %3d, %d%d\n", x, y, x+y");/*prints nums 4, 59*//*prints nums 4, 59*/
ff realreal(float)(float)
float p = 1.3/9, q = 2.875;float p = 1.3/9, q = 2.875;printf ("%7.4f %0.3f %1.0f %f\n", p, p, q, q);printf ("%7.4f %0.3f %1.0f %f\n", p, p, q, q);/* prints 0.1444 0.144 3 2.875000 *//* prints 0.1444 0.144 3 2.875000 */
lflf real (double)real (double) double p = 1.3/9, q = 2.875;double p = 1.3/9, q = 2.875;printf ("%7.4lf %0.3lf %1.0lf %lf\n", p, p, q, printf ("%7.4lf %0.3lf %1.0lf %lf\n", p, p, q, q);q);/* prints 0.1444 0.144 3 2.875000 *//* prints 0.1444 0.144 3 2.875000 */
cc charactercharacter(char)(char)
char letter = (char)('a' + 4);char letter = (char)('a' + 4);printf ("%c %d\n", letter, letter); printf ("%c %d\n", letter, letter); /* prints e 101 *//* prints e 101 */
ss stringstring(char *)(char *)
char *isString = "is";char *isString = "is";printf("This %s my string\n", isString);printf("This %s my string\n", isString);/* prints This is my string! *//* prints This is my string! */
ee realreal (scientific (scientific notation)notation)
double c = 62345892478;double c = 62345892478;printf("%0.2f %0.3e %14.1e", c, c, c);printf("%0.2f %0.3e %14.1e", c, c, c);62345892478.00 6.235e+010 6.2e+01062345892478.00 6.235e+010 6.2e+010
pp pointerpointer int x = 10; printf("%p", &x) int x = 10; printf("%p", &x) 0022FF580022FF58
Example of inputExample of input
To read input from user in C, use To read input from user in C, use scanf()scanf()
Syntax: Syntax: scanf(<formatString>, <pointer>, scanf(<formatString>, <pointer>, …)…)
Example:Example:
double f, g;double f, g;printf("Enter two real numbers separated by a comma:");printf("Enter two real numbers separated by a comma:");fflush(stdout);fflush(stdout);scanf("%lf,%lf", &f, &g);scanf("%lf,%lf", &f, &g);printf("Average: %5.2f\n", (f + g)/2.0);printf("Average: %5.2f\n", (f + g)/2.0);
Together…Together…
1.1. Let’s modify the program to get the Let’s modify the program to get the array elements from the user.array elements from the user.
2.2. Let’s create a new program to Let’s create a new program to compute the gcd of two numbers.compute the gcd of two numbers.
Some header files for the Some header files for the C LibraryC Library
Header Header FileFile
DescriptionDescription ExamplesExamples
stdio.hstdio.h Standard input/output Standard input/output from console and filesfrom console and files
prinf, scanf, fprintf, fflush, prinf, scanf, fprintf, fflush, sprintf, stdout, stdin, stderrsprintf, stdout, stdin, stderr
ctype.hctype.h Character typeCharacter type isdigit, isalpha, islower, isdigit, isalpha, islower, touppertoupper
float.hfloat.h max and min sizes of max and min sizes of real #sreal #s
DBL_MAX, FLT_MIN, DBL_DIGDBL_MAX, FLT_MIN, DBL_DIG
limits.hlimits.h max and min sizes of max and min sizes of integersintegers
INT_MAX, UINT_MAX, INT_MAX, UINT_MAX, LONG_MINLONG_MIN
math.hmath.h math constants and math constants and functionsfunctions
M_PI, M_E, M_PI, M_E, cos, exp, powcos, exp, pow
stdlib.hstdlib.h misc useful definitionsmisc useful definitions NULL, RAND_MAX, NULL, RAND_MAX, strtod, strtod, strtol, rand, srand, malloc, strtol, rand, srand, malloc, free, exit, qsort, bsearch, free, exit, qsort, bsearch, abs, itoaabs, itoa
string.hstring.h Character string Character string operationsoperations
strlen, strcpy, strcat, strlen, strcpy, strcat, strcmpstrcmp
time.htime.h Time and Clock Time and Clock operationsoperations
clock, time, difftime, clock, time, difftime, localtimelocaltime
C library references: http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html
More referencesMore references
HereHere
Pre-processor directivesPre-processor directives
A preprocessor is a program that examines C code A preprocessor is a program that examines C code before it is compiled and manipulates it in various ways: before it is compiled and manipulates it in various ways: To include external files using To include external files using #include#include
#include <stdio.h>#include <stdio.h>
#include “MyNode.h”#include “MyNode.h”
To define macros (names that are expanded by the To define macros (names that are expanded by the preprocessor into pieces of text or C code) using preprocessor into pieces of text or C code) using #define#define
#define MAX_SIZE 1024#define MAX_SIZE 1024 #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MIN(a,b) ((a) < (b) ? (a) : (b)) // do in program // do in program
togethertogether Just a substitution, not evaluated by the pre-processorJust a substitution, not evaluated by the pre-processor
Simple Simple data-data-typestypes
#bytes #bytes (typical)(typical)
charchar 11
shortshort 22
intint 44
longlong 44
floatfloat 44
doubledouble 88
Simple Data TypesSimple Data Types
Note: no boolean type!In C, we use ints
instead: 0: false, everything else: true.
An ugly infinite loop:An ugly infinite loop:intint y = 20; y = 20;intint x = (y > 10); x = (y > 10);whilewhile (x) { (x) {printf("hi\n");printf("hi\n");
}}
TypecastingTypecasting
As in Java:As in Java:
printf("sqrt(%d), rounded down, is %d\printf("sqrt(%d), rounded down, is %d\n", n",
17, (17, (intint)sqrt(17));)sqrt(17));
17, rounded down, is 417, rounded down, is 4
typedeftypedef In addition to defining constants using In addition to defining constants using
#define, we can also define types so #define, we can also define types so that our programs can more easily say that our programs can more easily say what we mean.what we mean.typedef int coinValue;coinValue quarter = 25; nickel = 5;
We could make our own boolean type:We could make our own boolean type:typedef int boolean;#define TRUE 1#define FALSE 0
boolean done = FALSE;if (done) { … }
BreakBreak
structsstructs No classes and objects in C.No classes and objects in C.
Can't encapsulate data and operations together.Can't encapsulate data and operations together. Two ways of grouping data:Two ways of grouping data:
Array: group several data elements of the same Array: group several data elements of the same type.type. Access individual elements by position: Access individual elements by position: students[i]students[i]
Struct: group related data that may be of Struct: group related data that may be of different typesdifferent types Access individual elements by name: Access individual elements by name: students.gpastudents.gpa
Example: Student struct Example: Student struct typetype
Declare the type:Declare the type: typedef structtypedef struct {{
charchar *name;*name;intint year;year;doubledouble gpa; gpa;
} Student;} Student;
Function to print a student's info:Function to print a student's info: voidvoid printStudent(Student s) {printStudent(Student s) { printf("[%s %d %1.2lf]\n", printf("[%s %d %1.2lf]\n", s.name, s.year, s.gpa); s.name, s.year, s.gpa);}}
Notice that once the type has been Notice that once the type has been declared, it can be used in the same declared, it can be used in the same way that a built-in type name is used.way that a built-in type name is used.
InitializingInitializingStudent juan;Student juan;juan.name = “Juan”juan.name = “Juan”juan.year = 2008;juan.year = 2008;juan.gpa = 3.2;juan.gpa = 3.2;
No constructors in C, but we can No constructors in C, but we can fake one:fake one:
Student makeStudent(char *name, int year, Student makeStudent(char *name, int year, int gpa) {int gpa) {Student stu;Student stu;stu.name = name;stu.name = name;stu.year = year;stu.year = year;stu.gpa = gpa;stu.gpa = gpa;return stu;return stu;
}}
typedef structtypedef struct {{charchar *name;*name;intint year;year;doubledouble gpa; gpa;
} Student;} Student;
Shorter:Shorter:
Student juan = {“Juan”, 2008, Student juan = {“Juan”, 2008, 3.2};3.2};
(Only when declare and define (Only when declare and define together, like arrays in Java.)together, like arrays in Java.)
Arrays and structsArrays and structsStudent students[10];Student students[10];students[0] = makeStudent(“Ryan”, students[0] = makeStudent(“Ryan”,
2011, 2.8);2011, 2.8);students[1] = makeStudent(“Mara”, students[1] = makeStudent(“Mara”,
2010, 3.5);2010, 3.5); students[0].namestudents[0].name ________________________________________students.name[0]students.name[0] ________________________________________
students[0].name[0]students[0].name[0]________________________________________
typedef structtypedef struct {{charchar *name;*name;intint year;year;doubledouble gpa; gpa;
} Student;} Student;
ExerciseExercise
Checkout the StructsIntro project Checkout the StructsIntro project from the reposfrom the repos
Read it over and run it to see another Read it over and run it to see another live code example of structslive code example of structs
Add the required functionAdd the required function Then Then sssttttrrretch sssttttrrretch break.break. Then you can look at the CProjects Then you can look at the CProjects
programs in the Projects folder on programs in the Projects folder on Angel.Angel.
What’s next?What’s next?
You should be able to do CProject, You should be able to do CProject, #1 (ThatsPerfect) after today’s #1 (ThatsPerfect) after today’s session.session.
But that’s last priorityBut that’s last priority There are links to C and to the There are links to C and to the gdbgdb
debugger from the project page.debugger from the project page.
User-defined header filesUser-defined header files Structures and other data structures may be defined Structures and other data structures may be defined
in a header file, for better organization of the code. in a header file, for better organization of the code. These are user-defined header files e.g. student.hThese are user-defined header files e.g. student.h To create one in Eclipse, choose File > New > Header To create one in Eclipse, choose File > New > Header
FileFile It stubs in:It stubs in:#ifndef#ifndef HD_H_ HD_H_
#define#define HD_H_ HD_H_
(write your code here)(write your code here)
#endif#endif /*HD_H_*/ /*HD_H_*/ To use it:To use it:
#include ``student.h’’#include ``student.h’’ at the start of your program file.at the start of your program file.
typedef structtypedef struct {{charchar *name;*name;intint year;year;doubledouble gpa; gpa;
} Student;} Student;
Command line Command line argumentsarguments
Accept inputs through the command Accept inputs through the command line.line.
main(int argc, char* argv[])main(int argc, char* argv[]) argc – argument countargc – argument count argv[] – value of each argumentargv[] – value of each argument
Example 7Example 7#include <stdio.h>#include <stdio.h>
int main(int argc, char *argv[]){int main(int argc, char *argv[]){ int count = 0;int count = 0; if(argc < 2){if(argc < 2){ printf("Must enter at least one argument\n");printf("Must enter at least one argument\n"); printf("Example: ./a.out this is program 7\n");printf("Example: ./a.out this is program 7\n"); exit(1);exit(1); }} printf(" The number of arguments is %d\n", argc);printf(" The number of arguments is %d\n", argc); printf("And they are :\n");printf("And they are :\n"); while(count < argc){while(count < argc){ printf("argv[%d]: %s\n",count,argv[count] );printf("argv[%d]: %s\n",count,argv[count] ); count++;count++; }} printf("\n");printf("\n"); return 0;return 0;}}
Run the program example7.c. Do not make any changes to the program (unless the program does not compile). Compile the program. Run the program correctly at least once and then write the output of the program in the space provided below.
Types of filesTypes of files
C source files (.c)C source files (.c) C header files (.h)C header files (.h) Object files (.o)Object files (.o) Executable files (typically no Executable files (typically no
extension – by default : a.out)extension – by default : a.out) Library files Library files
.a (archived) .a (archived) .so (shared object).so (shared object)
Creating an executableCreating an executable
Source: http://www.eng.hawaii.edu/Tutor/Make/1-2.html