300 likes | 406 Views
CSSE221: Software Dev. Honors Day 26. Announcements Simulation Project due tomorrow night Details of what should go into Executive Summary are posted Final Partner Accountability Survey is posted Hopefully, you checked C installation in Eclipse by now, and written “Hello World”.
E N D
CSSE221: Software Dev. Honors Day 26 • Announcements • Simulation Project due tomorrow night • Details of what should go into Executive Summary are posted • Final Partner Accountability Survey is posted • Hopefully, you checked C installation in Eclipse by now, and written “Hello World”.
This week: Intro to C • Monday: • Project day • Tuesday: • Introduction to C • Similarities to Java • Lots of little differences • structs • files • Thursday: • Pointers and dynamic memory allocation in C
Why learn C? • Intrinsic benefit • Low-level control of hardware and operating system • CPEs and EEs tend to use often • Fast! • Opens doors in future • Graphics (OpenGL library), Fractals, Operating Systems, and Networks courses • Lots of employers like C/C++ • Helps differentiate programming concepts from language • But power at a price: • No garbage collection: need to do your own memory management • Can overwrite memory • More room for mistakes • Some will love it, others won’t. • Ready?
C Java My First C Program
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; Similarities
Java Methods I/O: println importjava.lang.Arrays arrays 2D arrays static final MAX_LEN = 10; C Functions printf #include <stdio.h> arrays (but constant size) same: int points[3][4]; #define MAX_LEN 10 More Similarities
Major differences • I/O (printf, scanf) uses format strings • C has structs, not classes. • Can hold data but no methods • No classes means no String class. • A string is just an array of characters • Tricky-to-use string functions. • Reference variables are explicit: called pointers. • Can be used even for primitives
Formatted printing char name[] = "Bob"; int x = 17; printf("Hello there, %s. Your favorite " " number is %d and its square root is " "%4.2f\n", name, x, sqrt(x)); printf("Hello there, %s.\n\tYour " "\"favorite\" number is %d and its square " "root is %4.2f\n", name, x, sqrt(x));
Example of input To read input from user in C, use scanf() Syntax: scanf(<formatString>, <pointer>, …) Example:double f, g;printf("Enter two real numbers separated by a comma:");fflush(stdout);scanf("%lf,%lf", &f, &g);printf("Average: %5.2f\n", (f + g)/2.0);
Together… • Let’s modify the program to get the array elements from the user. • Let’s create a new program to compute the gcd of two numbers.
Some header files for the C Library C library references: http://www.utas.edu.au/infosys/info/documentation/C/CStdLib.html
More references • Here
Pre-processor directives • A preprocessor is a program that examines C code before it is compiled and manipulates it in various ways: • To include external files using #include #include <stdio.h> #include “MyNode.h” • To define macros (names that are expanded by the preprocessor into pieces of text or C code) using #define • #define MAX_SIZE 1024 • #define MIN(a,b) ((a) < (b) ? (a) : (b)) // do in program together • Just a substitution, not evaluated by the pre-processor
Simple Data Types Note: no boolean type! In C, we use ints instead: 0: false, everything else: true. An ugly infinite loop: int y = 20; int x = (y > 10); while (x) { printf("hi\n"); }
Typecasting As in Java: printf("sqrt(%d), rounded down, is %d\n", 17, (int)sqrt(17)); 17, rounded down, is 4
typedef • In addition to defining constants using #define, we can also define types so that our programs can more easily say what we mean. typedef int coinValue; coinValue quarter = 25; nickel = 5; • We could make our own boolean type: typedef int boolean; #define TRUE 1 #define FALSE 0 boolean done = FALSE; if (done) { … }
structs • No classes and objects in C. • Can't encapsulate data and operations together. • Two ways of grouping data: • Array: group several data elements of the same type. • Access individual elements by position: students[i] • Struct: group related data that may be of different types • Access individual elements by name: students.gpa
Example: Student struct type • Declare the type: • typedef struct{char*name;intyear;doublegpa; } Student; • Function to print a student's info: • voidprintStudent(Student s) { printf("[%s %d %1.2lf]\n", s.name, s.year, s.gpa);} • Notice that once the type has been declared, it can be used in the same way that a built-in type name is used.
Student juan; juan.name = “Juan” juan.year = 2008; juan.gpa = 3.2; No constructors in C, but we can fake one: Student makeStudent(char *name, int year, int gpa) { Student stu; stu.name = name; stu.year = year; stu.gpa = gpa; return stu; } typedef struct{ char*name;intyear;doublegpa; } Student; Initializing Shorter: Student juan = {“Juan”, 2008, 3.2}; (Only when declare and define together, like arrays in Java.)
Student students[10]; students[0] = makeStudent(“Ryan”, 2011, 2.8); students[1] = makeStudent(“Mara”, 2010, 3.5); students[0].name ____________________ students.name[0] ____________________ students[0].name[0] ____________________ typedef struct{ char*name;intyear;doublegpa; } Student; Arrays and structs
Exercise • Checkout the StructsIntro project from the repos • Read it over and run it to see another live code example of structs • Add the required function • Then sssttttrrretch break. • Then you can look at the CProjects programs in the Projects folder on Angel.
What’s next? • You should be able to do CProject, #1 (ThatsPerfect) after today’s session. • But that’s last priority • There are links to C and to the gdb debugger from the project page.
User-defined header files • Structures and other data structures may be defined in a header file, for better organization of the code. • These are user-defined header files e.g. student.h • To create one in Eclipse, choose File > New > Header File • It stubs in: #ifndef HD_H_ #define HD_H_ (write your code here) #endif /*HD_H_*/ • To use it: #include ``student.h’’ at the start of your program file. typedef struct{ char*name;intyear;doublegpa; } Student;
Command line arguments • Accept inputs through the command line. • main(int argc, char* argv[]) • argc – argument count • argv[] – value of each argument
Example 7 #include <stdio.h> int main(int argc, char *argv[]){ int count = 0; if(argc < 2){ printf("Must enter at least one argument\n"); printf("Example: ./a.out this is program 7\n"); exit(1); } printf(" The number of arguments is %d\n", argc); printf("And they are :\n"); while(count < argc){ printf("argv[%d]: %s\n",count,argv[count] ); count++; } printf("\n"); 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 files • C source files (.c) • C header files (.h) • Object files (.o) • Executable files (typically no extension – by default : a.out) • Library files • .a (archived) • .so (shared object)
Creating an executable Source: http://www.eng.hawaii.edu/Tutor/Make/1-2.html