CSSE221: Software Dev. Honors CSSE221: Software Dev. Honors Day 26 Day 26 Announcements Announcements Simulation Project due tomorrow Simulation Project due tomorrow night night Details of what should go into Details of what should go into Executive Summary are posted Executive Summary are posted Final Partner Accountability Final Partner Accountability Survey is posted Survey is posted Hopefully, you checked C Hopefully, you checked C installation in Eclipse by now, installation in Eclipse by now, and written “Hello World”. and written “Hello World”.
30
Embed
CSSE221: Software Dev. Honors Day 26 Announcements Announcements Simulation Project due tomorrow night Simulation Project due tomorrow night Details of.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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
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 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
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
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.
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.
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