Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages Java is an...

27
Programming in C Variables, Controls, Functions Variables, Controls, Functions

Transcript of Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages Java is an...

Page 1: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

Programming in C

Variables, Controls, FunctionsVariables, Controls, Functions

Page 2: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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, ciel)– 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, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Hello WorldIn JAVA -- Hello.java is in a classIn JAVA -- Hello.java is in a classpackage hello;package hello;public class Hellopublic class Hello{{

public static void main( String[ ] args )public static void main( String[ ] args ){{

System.out.println( “Hello World” );System.out.println( “Hello World” );}}

}}

In C -- Hello.c stands aloneIn C -- Hello.c stands alone#include <stdio.h>#include <stdio.h>int main( ) int main( ) {{

printf( “Hello World\n” );printf( “Hello World\n” );return 0;return 0;

}}

Page 5: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Compiling and Runninga Java Program

JavaCode

JavaBytecode

JRE for Linux

JRE for Windows

Java compiler

Hello.java

javac Hello.java

Hello.class

java Hello

java Hello

Java interpreter translates bytecode to machine code in JRE

unix> javac -d . *.java

unix> java hello.Hello

Page 6: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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 -o hello hello.c

unix> hello

Page 7: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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

Page 8: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Data Types

• Both languages support the integral types Both languages support the integral types intint, , shortshort, , longlong..• Both languages support the floating point typesBoth languages support the floating point types doubledouble andand

floatfloat• Both languages support the character data typeBoth languages support the character data type charchar• Both languages support the Boolean data typeBoth languages support the Boolean data type boolbool**

• Both languages support Both languages support enumenumss• C allows the C allows the signed signed (default) and(default) and unsigned unsigned qualifiers for qualifiers for

integral types (integral types (char, int, short, long)char, int, short, long)• C does C does NOTNOT support support bytebyte (use (use charchar instead) instead)• Both languages support arrays using [ ] and indexing starting with Both languages support arrays using [ ] and indexing starting with

zero (0).zero (0).

* bool is a built-in type in Java. bool is available with the current C99 standard, but requires <stdbool.h>* bool is a built-in type in Java. bool is available with the current C99 standard, but requires <stdbool.h>

Page 9: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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 10: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Logical Operators

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

Boolean Logic PracticeBoolean Logic Practice

Page 11: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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 ( {, } ) begin and end of blocks

Loop PracticeLoop Practice

Page 12: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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”)

printf(“x is %s greater than y”, (x <= y ? “ not “ : “”));

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

*much more on these later

Page 13: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Functions and 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– Have (optional) parameters– Pass arguments “by value”

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

*more on this later*more on this later

Page 14: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

C Function Examples/* returns the average of two integer parameters *//* returns the average of two integer parameters */

int average( int a, int b )int average( int a, int b )

{{

return ( (a + b) / 2 );return ( (a + b) / 2 );

}}

/* Simulates dog barking *//* Simulates dog barking */

void bark (int nrTimes)void bark (int nrTimes)

{{

int n;int n;

for (n = 0; n < nrTimes; n++)for (n = 0; n < nrTimes; n++)

printf(“Arf!\n”);printf(“Arf!\n”);

}}

Page 15: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Function Prototypes

• A function prototype defines the function’s name, A function prototype defines the function’s name, return type, and parameters.return type, and parameters.

• For example from the previous slideFor example from the previous slideint average( int a, int b );

void bark( int n );

• Before a function may be called, you must provide Before a function may be called, you must provide its prototype (or the function itself) so that the C its prototype (or the function itself) so that the C compiler can verify the function is being called compiler can verify the function is being called correctly.correctly.

(note the semi-colon).

Page 16: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

A Simple C Program/* convertTemps.c *//* convertTemps.c */#include <stdio.h>#include <stdio.h>

/* prototype for CtoF *//* prototype for CtoF */double CtoF( double degreesCelsius);double CtoF( double degreesCelsius);

int main( )int main( ){{

int temp;int temp;for (temp = 0; temp < 100; temp += 20)for (temp = 0; temp < 100; temp += 20)

printf(“%2d degrees F = %5.2f degrees C\n”,printf(“%2d degrees F = %5.2f degrees C\n”,temp, CtoF( temp ));temp, CtoF( temp ));

return 0;return 0;}}

/* converts temperature in Celsius to Fahrenheit *//* converts temperature in Celsius to Fahrenheit */double CtoF(double celsius) double CtoF(double celsius) {{

double fahrenheit; double fahrenheit; fahrenheit = 9.0 / 5.0 * celsius + 32;fahrenheit = 9.0 / 5.0 * celsius + 32;return fahrenheit;return fahrenheit;

} }

Page 17: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Typical C Program

includes #include <stdio.h>

double CtoF( double celcius);

int main( ){ int temp; for (temp = 0; temp < 100; temp += 20) printf(“%2d degrees F = %5.2f degrees C\n”,

temp, CtoF( temp )); return 0;}

/* converts temperature in Celsius to Fahrenheit */double CtoF(double celsius) { double fahrenheit; fahrenheit = 9.0 / 5.0 * celsius + 32; return fahrenheit;}

defines, data type definitions, global variable declarationsfunction prototypes

function definitions

main()

Page 18: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

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 “cccc”.”.

On the UMBC GL systems, use the GNU compiler On the UMBC GL systems, use the GNU compiler named “named “gccgcc”.”.

gcc –o convert convertTemps.cgcc –o convert convertTemps.c

tells the compiler tocreate executable file with the name convert

tells the compilerthe name of the inputfile.

Page 19: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Header Files• When a file contains functions to be reused in several When a file contains functions to be reused in several

programs, their prototypes and important #defines are programs, their prototypes and important #defines are usually placed into a header ( .h ) that is then #included usually placed into a header ( .h ) that is then #included where needed.where needed.

• Each .h file should be “stand alone”. That is, it should Each .h file should be “stand alone”. That is, it should #include any .h files it needs to avoid compiler errors.#include any .h files it needs to avoid compiler errors.

• In this example, the prototype for CtoF() would be placed In this example, the prototype for CtoF() would be placed into the file CtoF.h which would then be #included in into the file CtoF.h which would then be #included in convertTemps.c or any other .c file that used CtoF( ) convertTemps.c or any other .c file that used CtoF( )

• The code for CtoF( ) would be placed int CtoF.cThe code for CtoF( ) would be placed int CtoF.c

Page 20: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

CtoF.h

/* CtoF.h */

/* #includes needed by prototypes */

/* #defines needed for prototypes */

/* prototype for functions defined in CtoF.c */

double CtoF( double celsius );

Page 21: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

CtoF.c

/* CtoF.c */

/* necessary #includes, #defines */

/* converts temp in Celsius to Fahrenheit */

double CtoF(double celsius)

{

double fahrenheit;

fahrenheit = 9.0 / 5.0 * celsius + 32;

return fahrenheit;

}

Page 22: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

convertTemps.c revisited#include <stdio.h>#include “CtoF.h” /* note quotes */

int main( ){

int temp;for (temp = 0; temp < 100; temp += 20)

printf(“%2d degrees F = %5.2f degrees C\n”,

temp, CtoF( temp ));return 0;

}

Page 23: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Compiling and linking

• When a program’s code is separated into multiple .c files, When a program’s code is separated into multiple .c files, we must compile each .c file and then combine the we must compile each .c file and then combine the resulting .o files to create an executable program.resulting .o files to create an executable program.

• The files may be compiled separately and then linked together. The files may be compiled separately and then linked together. The -c flag in the first two command tells gcc to “compile only” The -c flag in the first two command tells gcc to “compile only” which results in the creation of .o (object) files. In the 3which results in the creation of .o (object) files. In the 3rdrd command, the presence of .o extension tells gcc to link the files command, the presence of .o extension tells gcc to link the files into an executableinto an executable

gcc -c myprogram.cgcc -c CtoF.cgcc -o myprogram myprogram.o CtoF.o

• Or it can be done all in one stepOr it can be done all in one step– gcc -o myprogram myprogram.c CtoF.c

Page 24: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Recursion

• C functions may be called recursively.C functions may be called recursively.– A function calls itself

• A properly written recursive function has the A properly written recursive function has the following propertiesfollowing properties– A “base case” - a condition which does NOT make a

recursive call because a simple solution exists– A recursive call with a condition (usually a parameter

value) that is closer to the base case than the condition (parameter value) of the current function call

• Each invocation of the function gets its own set Each invocation of the function gets its own set of arguments and local variablesof arguments and local variables

Page 25: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Recursion Example/* print an integer in decimal** K & R page 87 (may fail on largest negative int) */

#include <stdio.h>Void printd( int n ){

if ( n < 0 ){

printf( “-” );n = -n;

}if ( n / 10 ) /* more than 1 digit */

printd( n / 10 ); /* recursive call- n has 1 less digit */

printf( “%c”, n % 10 + ‘0’); /* base case --- 1 digit */}

Page 26: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Miscellaneous• CommentsComments

– Both languages support block comments surrounded by /* and */,

– C99 standard also supports // end-of-line style

• Declaring variablesDeclaring variables– Starting with the C99 standard, C variables may be

declared anywhere in the code, just like Java

• #defines#defines– C supports the definition of macros using #define

• #define MAX 42 // a simple name of an int

• More complex macros later

Page 27: Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

7/28/09

Java/C Project example

• Number Theory - a problem about integersNumber Theory - a problem about integers• http://www.cs.umbc.edu/courses/undergradaute/3http://www.cs.umbc.edu/courses/undergradaute/3

13/fall09/code/numbertheory.txt13/fall09/code/numbertheory.txt