Programming in C Variables, Controls, Arrays, Functions.

38
Programming in C Variables, Controls, Arrays, Variables, Controls, Arrays, Functions Functions

Transcript of Programming in C Variables, Controls, Arrays, Functions.

Page 1: Programming in C Variables, Controls, Arrays, Functions.

Programming in C

Variables, Controls, Arrays, FunctionsVariables, Controls, Arrays, Functions

Page 2: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Different Kinds of Languages

Java is an object-oriented programming (OOP) languageJava is an object-oriented programming (OOP) language Problem solving centers on defining classes that model “things” like

Trucks, Persons, Marbles, Strings, and CandyMachine Classes encapsulate data (instance variables) and code (methods)

C is a procedural languageC is a procedural language Problem solving centers on defining functions that perform a single

service like getValidInt( ), search( ) and inputPersonData( ). Data is global or passed to functions as parameters No classes

Page 3: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Libraries• Because Java is an OOP language, its libraries consist of Because Java is an OOP language, its libraries consist of

predefined classes that you can use in your applicationspredefined classes that you can use in your applications– ArrayList, Scanner, Color, Integer

• Because C is a procedural language, its library consists of Because C is a procedural language, its library consists of predefined functions.predefined functions.– Char/string functions (strcpy, strcmp)– Math functions (floor, ceil, sin)– Input/Output functions (printf, scanf)

• On-line C/Unix manual -- the “man” commandOn-line C/Unix manual -- the “man” command– Description of many C library functions and Unix commands– Usage: man <function name> for C library functions

or man <command name> for Unix commands• man printf• man dir

– Search for applicable man pages using the “apropos” command or “man -k”

– Learn to use the man command using “man man”

Page 4: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

The C Standard• The first standard for C was published by the American The first standard for C was published by the American

National Standards Institute (ANSI) in 1989 and is widely National Standards Institute (ANSI) in 1989 and is widely referred to as “ANSI C” (or sometimes C89)referred to as “ANSI C” (or sometimes C89)

• A slightly modified version of the ANSI C standard was A slightly modified version of the ANSI C standard was adopted in 1990 and is referred to as “C90”. “C89" and adopted in 1990 and is referred to as “C90”. “C89" and "C90" refer to essentially the same language."C90" refer to essentially the same language.

• In March 2000, ANSI adopted the ISO/IEC 9899:1999 In March 2000, ANSI adopted the ISO/IEC 9899:1999 standard. This standard is commonly referred to as C99, standard. This standard is commonly referred to as C99, and it is the current standard for the C programming and it is the current standard for the C programming language.language.

• The C99 standard is not fully implemented in all versions of The C99 standard is not fully implemented in all versions of C compilers.C compilers.

Page 5: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

C99 on GL• The GNU C compiler on the GL systems (gcc The GNU C compiler on the GL systems (gcc

version 4.1.2) appears to support several useful version 4.1.2) appears to support several useful C99 features.C99 features.

• These notes include those C99 features These notes include those C99 features supported by gcc on GL since our course use supported by gcc on GL since our course use that compiler.that compiler.

• These features will be noted as C99 features These features will be noted as C99 features when presented.when presented.

Page 6: Programming in C Variables, Controls, Arrays, Functions.

7/27/10

Hello WorldThis source code is in a file such as hello.cThis source code is in a file such as hello.c

/* /* file header block comment file header block comment

*/*/#include <stdio.h>#include <stdio.h>int main( )int main( ){{// print the greeing ( C99 )// print the greeing ( C99 )printf( “Hello World\n”);printf( “Hello World\n”);return 0;return 0;

}}

Page 7: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Compiling on Unix

Traditionally the name of the C compiler that comes Traditionally the name of the C compiler that comes with Unix is “with Unix is “cc”.”.

The UMBC GL systems use the “GNU Compiler The UMBC GL systems use the “GNU Compiler Collection” named “Collection” named “gcc” for compiling C (and C+” for compiling C (and C++) programs.+) programs.

The default name of the executable program that is The default name of the executable program that is created by created by gcc is is a.out

unixunix> > gcc hello.c

Page 8: Programming in C Variables, Controls, Arrays, Functions.

1/13/10

Compiler Options• -c-c

– Compile only (create a .o file), don’t link (create an executable)gcc -c hello.c

• -o filename-o filename– Name the executable filename instead of a.outgcc -o hello hello.cgcc -o hello hello.c

• -Wall-Wall– Report all warningsgcc -Wall hello.cgcc -Wall hello.c

• Use them togetherUse them togethergcc -Wall -o hello hello.cgcc -Wall -o hello hello.c

• Note: the Note: the -ansi-ansi switch enforces the original ANSI C switch enforces the original ANSI C standard and disables C99 features.standard and disables C99 features.

Page 9: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Compiling and Running a C Program

Pre-processor

(cpp)

hello.i Compiler(cc1)

hello.s Assembler(as)

hello.o Linker(ld)

hellohello.c

Sourceprogram(text)

Modifiedsourceprogram(text)

Assemblyprogram(text)

Relocatableobject

programs(binary)

Executableobjectprogram(binary)

printf.o

unix> gcc -Wall -o hello hello.c

Execute your program by typing the name of the executableat the Unix prompt

unix> hello

Page 10: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Language Commonality

• C and Java syntax have much in commonC and Java syntax have much in common– Some Data Types– Arithmetic operators– Logical Operators – Control structures– Other Operators

• We assume that you are proficient in JavaWe assume that you are proficient in Java

Page 11: Programming in C Variables, Controls, Arrays, Functions.

7/26/10

Integral Data Types• C data types for storing integer values areC data types for storing integer values are

– int (the basic integer data type)

– short int (typically abbreviated just as short)

– long int (typically abbreviated just as long)

– long long int (C99)

– char (C does not have “byte”)

• int should be used unless there’s a very good should be used unless there’s a very good reason to use one of the othersreason to use one of the others

• char is stored in 1 byte is stored in 1 byte• The number of bytes used by the other types The number of bytes used by the other types

depends on the machine being useddepends on the machine being used

Page 12: Programming in C Variables, Controls, Arrays, Functions.

7/27/10

Integral Type Sizes• The C standard is specifically vague regarding The C standard is specifically vague regarding

the size of the integral typesthe size of the integral types– A short int must not be larger than an int.

– An int must not be larger than a long int.

– A short int must be at least 16 bits long.

– An int must be at least 16 bits long.

– A long int must be at least 32 bits long.

– A long long int must be at least 64 bits long.

• The standard does not require that any of these The standard does not require that any of these sizes be necessarily different. sizes be necessarily different.

Page 13: Programming in C Variables, Controls, Arrays, Functions.

7/26/10

Integral Specifiers

• Each of the integral types may be specified as Each of the integral types may be specified as eithereither– signed (positive, negative, or zero)

– unsigned (positive or zero only)

• signed is the default qualifier is the default qualifier• Much more on this laterMuch more on this later

Page 14: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Integral Variables

• Each of the following is a valid variable Each of the following is a valid variable declarationdeclaration

int age = 42;

signed int age = -33;

long area = 123456;

short int height = 4;

unsigned char IQ = 102;

unsigned int length = 8282;

unsigned long int SATscore = 800;

Page 15: Programming in C Variables, Controls, Arrays, Functions.

7/26/10

Floating Point Data Types

• C data types for storing floating point values C data types for storing floating point values (those with a decimal part) are(those with a decimal part) are– float, the smallest floating point type

– double, a larger type with a larger range of values

– long double, an even larger type with an even large range of values

• double is typically used for all floating point is typically used for all floating point values unless there’s a compelling need to use values unless there’s a compelling need to use one of the othersone of the others

• Floating point variables may store integer valuesFloating point variables may store integer values

Page 16: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Size of Floating Point Type

• A A double variable can be marked as being a variable can be marked as being a long double, which the compiler may use to select a , which the compiler may use to select a larger floating point representation than a plain larger floating point representation than a plain double. .

• The standard is unspecific on the relative sizes of The standard is unspecific on the relative sizes of the floating point values, and only requires a the floating point values, and only requires a float not to be larger than a not to be larger than a double, which , which should not be should not be larger than a than a long double..

Page 17: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Floating Point Declarations

• Each of the following is a valid floating point Each of the following is a valid floating point variable declarationvariable declaration

float avg = 10.6;

double median = 88.54;

double homeCost = 10000;

Page 18: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Character Data Types

• C has just one data type for storing charactersC has just one data type for storing characters– char, which is just one byte

• Because a Because a char is just one byte, C only supports is just one byte, C only supports the ASCII character set (more on this later)the ASCII character set (more on this later)

Page 19: Programming in C Variables, Controls, Arrays, Functions.

sizeof( ) • Because the sizes (number of bits/bytes) of the C Because the sizes (number of bits/bytes) of the C

data types are vaguely specified, C provides the data types are vaguely specified, C provides the sizeof( ) operator to determine the size of any operator to determine the size of any data type (data type (inin bytesbytes).).

• sizeof( ) should be used everywhere the size should be used everywhere the size of a data type is required so that your code is of a data type is required so that your code is portable to other hardware on which the size of portable to other hardware on which the size of the data types may be different.the data types may be different.

• On GL,On GL,– sizeof( short ) = 2– sizeof( int ) = sizeof( long ) = 4– sizeof (long long) = 8– sizeof( float ) = 4– sizeof( double ) = 8

Page 20: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

const Qualifier

• Any of the variable types found above may be Any of the variable types found above may be qualified as qualified as const..

• const variables may not be modified by your variables may not be modified by your code. Any attempt to do so will result in a code. Any attempt to do so will result in a compiler error.compiler error.

• Since they may not be modified, Since they may not be modified, const variables variables must be initialized when declaredmust be initialized when declaredconst double PI = 3.1415;

const int myAge = 39;

Page 21: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Variable Declaration

• ANSI C requires that all variables be declared at ANSI C requires that all variables be declared at the beginning of the “block” in which they are the beginning of the “block” in which they are defined, before any executable line of code.defined, before any executable line of code.

• C99 allows variables to be declared anywhere in C99 allows variables to be declared anywhere in the code (like Java and C++)the code (like Java and C++)

• In any case, variables must be declared before In any case, variables must be declared before they can be used.they can be used.

Page 22: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Arithmetic Operators

Arithmetic operators are the sameArithmetic operators are the same= is used for assignment

+, -, (plus, minus)

*, /, % (times, divide, mod)

++, -- (increment, decrement (pre and post))

Combinations are the sameCombinations are the same+=, -=, (plus equal, minus equal)

*=, /=, %= (times equal, divide equal, mod equal)

Arithmetic PracticeArithmetic Practice Assignment PracticeAssignment Practice

Page 23: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Boolean Data Type• ANSI C has no Boolean type ANSI C has no Boolean type • The C99 standard supports the Boolean data typeThe C99 standard supports the Boolean data type• To use To use bool, , true, and , and false, your code must , your code must

include include <stdbool.h>

#include <stdbool.h>

bool isRaining = false;

if ( isRaining )

printf( “Bring your umbrella\n”);

Page 24: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Logical Operators

Logical operators are the same in C and Java and result in a Logical operators are the same in C and Java and result in a Boolean value.Boolean value. && (and) || (or) ==, != (equal and not equal) <, <= (less than, less than or equal) >, >= (greater than, greater than or equal)

• Integral types may also be treated as Boolean expressionsIntegral types may also be treated as Boolean expressions– Zero is considered “false”– Any non-zero value is considered “true”

Boolean Logic PracticeBoolean Logic Practice

Page 25: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Control Structures

Both languages support these control structures Both languages support these control structures which function the same way in C and Javawhich function the same way in C and Java for loops

But NOT -- for (int i = 0; i < size; i++) while loops do-while loops switch statements if and if-else statements braces ( {, } ) are used to begin and end blocks

Loop PracticeLoop Practice

Page 26: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Other Operators

These other operators are the same in C and JavaThese other operators are the same in C and Java ?: (tri-nary “hook colon”)

int larger = (x > y ? x : y);

<<, >>, &, |, ^ (bit operators*) <<=, >>=, &=, |=,^= [ ] (brackets for arrays) ( ) parenthesis for functions and type casting

*much more on these later

Page 27: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Arrays• Like most languages, C supports arrays as a Like most languages, C supports arrays as a

basic data structure.basic data structure.• Array indexing starts with 0.Array indexing starts with 0.• ANSI C requires that the size of the array be a ANSI C requires that the size of the array be a

constant (if specified)constant (if specified)• Declaring and initializing arraysDeclaring and initializing arrays

int grades[44];

int areas[10] = {1, 2, 3};

long widths[12] = {0};

int IQs[ ] = {120, 121, 99, 154};

Page 28: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Variable Size Arrays

• C99 allows the size of an array to be a variableC99 allows the size of an array to be a variableint nrStudents = 30;

. . .

int grades[nrStudents];

Page 29: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

2-D Arrays

• Like most languages, C supports multi-Like most languages, C supports multi-dimensional arraydimensional array

• Subscripting is provided for each dimensionSubscripting is provided for each dimension• For 2-d arrays, the first dimension is the number For 2-d arrays, the first dimension is the number

of “rows”, the second is the number of of “rows”, the second is the number of “columns” in each row“columns” in each rowint board[ 4 ] [ 5 ]; // 4 rows, 5 columns

int x = board[ 0 ][ 0 ]; // 1st row, 1st column

int y = board[ 3 ][ 4 ]; // 4th (last) row, 5th (last) column

Page 30: Programming in C Variables, Controls, Arrays, Functions.

1/13/10

#defines• The The #define directive can be used to give names to directive can be used to give names to

important constants in your code. This makes your code important constants in your code. This makes your code more readable and more easily changeable.more readable and more easily changeable.

• The compiler’s preprocessor replaces every instance of the The compiler’s preprocessor replaces every instance of the #define name with the text that it represents. name with the text that it represents.

• Note that there is no terminating semi-colonNote that there is no terminating semi-colon

#define MIN_AGE 21#define MIN_AGE 21......

if (myAge > MIN_AGE)if (myAge > MIN_AGE)......

#define PI 3.1415#define PI 3.1415......double area = PI * radius * radius;double area = PI * radius * radius;......

Page 31: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

#define vs const

• #define #define – Pro: no memory is used for the constant– Con: cannot be seen when code is compiled since they

are removed by the pre-compiler– Con: are not real variables and have no type

• const variablesconst variables– Pro: are real variables with a type– Pro: can be examined by a debugger– Con: take up memory

Page 32: Programming in C Variables, Controls, Arrays, Functions.

1/13/10

typedefs• C allows you to define new names for existing C allows you to define new names for existing

data types (NOT new data types)data types (NOT new data types)• This feature can be used to give application-This feature can be used to give application-

specific names to simple typesspecific names to simple types

typedef int Temperature;

typedef int[3] Row;• Or to give simple names to complex typesOr to give simple names to complex types

- more on this later - more on this later• Using Using typedefs makes future changes easier makes future changes easier

and makes the code more relevant to the and makes the code more relevant to the applicationapplication

Page 33: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Enumeration Constants

• C provides the C provides the enum as a list of named constant integer as a list of named constant integer values (starting a 0 by default)values (starting a 0 by default)

• Behave like integersBehave like integers• Names in Names in enum must be distinct must be distinct• Often a better alternative to Often a better alternative to #defines• ExampleExample

enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };...

enum months thisMonth;thisMonth = SEP; // okthisMonth = 42; // unfortunately, also ok

Page 34: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Functions vs. Methods• Java classes include methods which can be called from any code Java classes include methods which can be called from any code

with appropriate access (recall with appropriate access (recall publicpublic methods) methods)

• C functions are like Java methods, but they don’t belong to any C functions are like Java methods, but they don’t belong to any class. Functions are defined in a file and may be either global to class. Functions are defined in a file and may be either global to your program or local to the file in which they are defined*.your program or local to the file in which they are defined*.

• Like Java methods, C functions Like Java methods, C functions – Have a name– Have a return type– May have parameters

*more on this later*more on this later

Page 35: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

More Functions• Before a function may be called, its “prototype” (aka Before a function may be called, its “prototype” (aka

signature -- name and parameters) must be known to the signature -- name and parameters) must be known to the compiler so that it can verify that your code is calling the compiler so that it can verify that your code is calling the function correctly.function correctly.

• This is accomplished in one of two waysThis is accomplished in one of two ways– Provide the entire function definition prior to the calling code

– Provide the function prototype prior to the calling code and provide the function definition elsewhere

• Unlike Java methods, a function in C is uniquely identified Unlike Java methods, a function in C is uniquely identified by its name. Therefore, there is no concept of method by its name. Therefore, there is no concept of method overloading in C as there is in Java. There can be only one overloading in C as there is in Java. There can be only one main( ) function in a C application. function in a C application.

• Our standards dictate that function names begin with and Our standards dictate that function names begin with and UPPERCASE letterUPPERCASE letter

Page 36: Programming in C Variables, Controls, Arrays, Functions.

7/27/10

A Simple C Program#include <stdio.h>typedef double Radius;#define PI 3.1415

/* given the radius, calculates the area of a circle */double CircleArea( Radius radius ){

return ( PI * radius * radius );}

// given the radius, calcs the circumference of a circledouble Circumference( Radius radius ){

return (2 * PI * radius );}

int main( ){

Radius radius = 4.5;double area = circleArea( radius );double circumference = Circumference( radius );

// print the resultsreturn 0;

}

Page 37: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Alternate Sample #include <stdio.h>typedef double Radius;#define PI 3.1415

/* function prototypes */double CircleArea( Radius radius );double Circumference( Radius radius );

int main( ){

Radius radius = 4.5;double area = circleArea( radius );double circumference = Circumference( radius );

// print the resultsreturn 0;

}

/* given the radius, calculates the area of a circle */double CircleArea( Radius radius ){

return ( PI * radius * radius );}

// given the radius, calcs the circumference of a circledouble Circumference( Radius radius ){

return (2 * PI * radius );}

Page 38: Programming in C Variables, Controls, Arrays, Functions.

7/28/09

Typical C Programincludes #include <stdio.h>

typedef double Radius;#define PI 3.1415

/* function prototypes */double CircleArea( Radius radius );double Circumference( Radius radius );

int main( ){ Radius radius = 4.5; double area = circleArea( radius ); double circumference = Circumference( radius );

// print the results return 0;}

/* given the radius, calculates the area of a circle */double CircleArea( Radius radius ){ return ( PI * radius * radius );}

// given the radius, calcs the circumference of a circledouble Circumference( Radius radius ){ return (2 * PI * radius );}

defines, typedefs, data type definitions, global variable declarationsfunction prototypes

function definitions

main()