Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes...

42
Overview of a C Program Programming with C CSCI 112, Spring 2015 Patrick Donnelly Montana State University

Transcript of Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes...

Page 1: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Overview of a C Program

Programming with C

CSCI 112, Spring 2015

Patrick Donnelly

Montana State University

Page 2: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

C Language Components

• Preprocessor Directives

• Comments

• The “main” function

• Variable Declarations and Data Types

• Executable Statements

• Reserved Words

• Identifiers

Programming with C (CSCI 112) Spring 2015 2 / 42

Page 3: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

General Outline of a C Program

preprocessor directives

main function heading {

declarations

executable statements

}

Programming with C (CSCI 112) Spring 2015 3 / 42

Page 4: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Example C Program

#include <stdio.h> // printf , scanf definitions

#define KMS_PER_MILE 1.609 // conversion constant

int main(int argc , char ** argv)

{

double miles; // distance in miles

double kms; // equivalent distance in kilometers

// get the distance in miles

printf("Enter the distance in miles > ");

scanf("%lf", &miles );

// convert the distance to kilometers

kms = KMS_PER_MILE * miles;

// display the distance in kilometers

printf("That equals %f kilometers .\n", kms);

return (0);

}

Programming with C (CSCI 112) Spring 2015 4 / 42

Page 5: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Anatomy of a C Program

Programming with C (CSCI 112) Spring 2015 5 / 42

Page 6: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Example C Program: Preprocessor Directives

#include <stdio.h>#define KMS PER MILE 1.609

int main(int argc , char ** argv)

{

double miles; // distance in miles

double kms; // equivalent distance in kilometers

// get the distance in miles

printf("Enter the distance in miles > ");

scanf("%lf", &miles );

// convert the distance to kilometers

kms = KMS_PER_MILE * miles;

// display the distance in kilometers

printf("That equals %f kilometers .\n", kms);

return (0);

}

Programming with C (CSCI 112) Spring 2015 6 / 42

Page 7: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Example C Program: Declarations

#include <stdio.h> // printf , scanf definitions

#define KMS_PER_MILE 1.609 // conversion constant

int main(int argc , char ** argv)

{

double miles;

double kms;

// get the distance in miles

printf("Enter the distance in miles > ");

scanf("%lf", &miles );

// convert the distance to kilometers

kms = KMS_PER_MILE * miles;

// display the distance in kilometers

printf("That equals %f kilometers .\n", kms);

return (0);

}

Programming with C (CSCI 112) Spring 2015 7 / 42

Page 8: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Example C Program: Comments

#include <stdio.h> // printf, scanf definitions

#define KMS_PER_MILE 1.609 // conversion constant

int main(int argc , char ** argv)

{

double miles; // distance in miles

double kms; // equivalent distance in kilometers

// get the distance in miles

printf("Enter the distance in miles > ");

scanf("%lf", &miles );

// convert the distance to kilometers

kms = KMS_PER_MILE * miles;

// display the distance in kilometers

printf("That equals %f kilometers .\n", kms);

}

Programming with C (CSCI 112) Spring 2015 8 / 42

Page 9: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Example C Program: Executable Statements

#include <stdio.h> // printf , scanf definitions

#define KMS_PER_MILE 1.609 // conversion constant

int main(int argc , char ** argv)

{

double miles; // distance in miles

double kms; // equivalent distance in kilometers

// get the distance in miles

printf("Enter the distance in miles> ");

scanf("%lf", &miles);

// convert the distance to kilometers

kms = KMS PER MILE * miles;

// display the distance in kilometers

printf("That equals %f kilometers.\n", kms);

return(0);

}

Programming with C (CSCI 112) Spring 2015 9 / 42

Page 10: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Our C Program

#include <stdio.h>

/* lab01.c (name of your file)

* Philip J. Fry (your name), CSCI112 , Lab 01

* 08/28/2014 (current date)

*/

int main(void) {

printf("Hello World\n");

return (0);

}

Programming with C (CSCI 112) Spring 2015 10 / 42

Page 11: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Preprocessor Directives

Definition: Preprocessor Directives

Preprocessor Directives are commands that give instructions tothe C preprocessor.

Definition: Preprocessor

The Preprocessor is a program that modifies your C programbefore it is compiled.

Preprocessor Directives start with a “#” symbol.

• #include

• #define

• #if

• #else

• #endif

• #pragma

Programming with C (CSCI 112) Spring 2015 11 / 42

Page 12: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

#include

#include is used to include other source files into your source file.

#include gives a program access to a library/header file.

• stdio.h

• math.h

• time.h

Libraries are a collection of useful functions and symbols.Standard libraries are predefined by the ANSI C language.

• You must include stdio.h if you want to use printf andscanf library functions.

• “#include <stdio.h>” inserts their definitions into yourprogram before compilation.

Programming with C (CSCI 112) Spring 2015 12 / 42

Page 13: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

#define

The #define directive instructs the preprocessor to replace everyoccurance of a particular text with a given constant value. Thereplacement occurs before compilation.

Your source code:

#de f i n e PI 3 .14159#d e f i n e EULERS NUMBER 2.71828i n t main ( vo i d ) {

doub l e x = 5 ∗ PI ;doub l e y = EULERS NUMBER ∗ 7 ;r e t u r n ( 0 ) ;

}

What actually gets compiled:

i n t main ( vo i d ) {doub l e x = 5 ∗ 3 . 14159 ;doub l e y = 2.71828 ∗ 7 ;r e t u r n ( 0 ) ;

}

Programming with C (CSCI 112) Spring 2015 13 / 42

Page 14: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Constants

#define Constants

• Consists of 3 parts:◦ “#define”◦ constant name◦ constant value

• There is no “=” sign or “;” at the end

#define MY_CONSTANT_NAME 123

#define ANSWER 42

Programming with C (CSCI 112) Spring 2015 14 / 42

Page 15: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Comments

Comments provide extra information, making it easier for humansto understand the program.

These comments are completely ignored by the compiler.

Comments take two forms:

• /* */ - anything between asterisks is a comment.• // - anything after is a comment, but only until EOL.

Comments are used for documentation that helps otherprogrammers read and understand the program.

Programs should contain a comment at the top with• the programmer’s name,• the date, and• a brief description of what the program does.

COMMENT YOUR CODE!Programming with C (CSCI 112) Spring 2015 15 / 42

Page 16: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

The “main” function

The heading “int main(void)” marks the beginning of the mainfunction where your program execution begins.

Every C program has a main function.

Braces/Curly brackets: { } mark the beginning and end of thebody of the function.

A function body has two parts:

• declarations: (names of variables and data types) tell thecompiler what memory cells are needed in the function andhow they should be processed.

• executable statements: they reflect “actions” of youralgorithm. These are translated into machine language by thecompiler and later executed.

Programming with C (CSCI 112) Spring 2015 16 / 42

Page 17: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Declarations of Variables

Variable: A memory cell used to store program data.

• A variables value can change with time.

• We use its name as a simple reference (instead of the actualaddress in memory).

Variable declaration: Statement that communicates to thecompiler the names of variables in the program and the data typethey represent.

Example:

double miles;

This tells the compiler to create a space for a variable of typedouble in memory and refer to it each time we use the name milesin our program.

Programming with C (CSCI 112) Spring 2015 17 / 42

Page 18: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Numeric Data Types

Definition: Data Type

Data Type: a set of values and a set of operations that can beperformed on those values.

Numeric Data Types:

• int: Stores integer value (whole number).Examples: 65, -123

• double: Stores real number (uses a decimal point).Examples: 3.14159, 1.23e5 (123000.0)

Arithmetic operations (+,-,*,/, %) can be used on ints anddoubles.

Programming with C (CSCI 112) Spring 2015 18 / 42

Page 19: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Character Data Type

Character Data Type:

• char: An individual character value.Examples: ‘a’, ,‘5’, ‘*’(can be a letter, digit, or special symbol)

Character Declaration• Use single quotes, NOT double quotes

char my_char = ’Z’;

Comparison operations (<,>,≤,≥) can be used on ints, doublesand chars.

Programming with C (CSCI 112) Spring 2015 19 / 42

Page 20: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

ASCII Code

‘A’ < ‘B’ < ‘C’ < ... < ‘X’ < ‘Y’ < ‘Z’

Programming with C (CSCI 112) Spring 2015 20 / 42

Page 21: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Executable Statements

Executable Statements: C statements used to write or code thealgorithm.

The C compiler translates the executable statements into machinecode.

Examples:

• Input/Output Operations and Functions◦ printf function◦ scanf function

• Assignment Statement (=)

• return Statement/Operation

Programming with C (CSCI 112) Spring 2015 21 / 42

Page 22: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Executable Statements: Input/Output Operations

Input operation: data transfer from outside the program intocomputer memory that is usable by the program.

Input may be received from:

• A program user

• An external file

• Another program

Output operation: program results that can be displayed to theprogram user.

Results can be printed to:

• The standard console output

• An external file

Programming with C (CSCI 112) Spring 2015 22 / 42

Page 23: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Executable Statements: Functions

A function takes input parameters and produces an output.

A function definition specifies the return type, the inputparameters, and the body.

A function call is used to call or activate a function.

• Calling a function means asking another piece of code to dosome work for you.

Programming with C (CSCI 112) Spring 2015 23 / 42

Page 24: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Executable Statements: Functions - printf()

By calling the printf() function, we are asking for the functionto print to standard output.

The first argument to printf is the formatting code (in stringform), and all following arguments are the the variables to be usedin the placeholders.

double miles = 2.7;

printf("That is %f miles.\n", miles );

Programming with C (CSCI 112) Spring 2015 24 / 42

Page 25: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Executable Statements: Functions - printf()

Multiple placeholders can be specified, and the correspondingarguments are then provided in order. Different types of variablesrequire different formatting codes.

int a = 1;

double b = 2.0;

char *c = "three";

printf("Easy as %d, %f, %s!\n", a, b, c);

Details on formatting codes can be found in the handout.

Programming with C (CSCI 112) Spring 2015 25 / 42

Page 26: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Executable Statements: Functions - scanf()

Reading input data in a program is done via the scanf() function.

The concept is very much the same as the printf() function.

In this case, the format code is just the variable code for what datawill be received (%d, %c, %lf), and the following arguments arethe variables that will receive the data.

double miles;

scanf("%lf", &miles );

The “&” is the address operator in C. The “&” operator in frontof variable miles informs the scanf() function about the locationof variable miles in the computer’s memory.

Programming with C (CSCI 112) Spring 2015 26 / 42

Page 27: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

printf()/scanf() statements

printf()/scanf() statements

Use commas to deliminate printf/scanf arguments.

char a = ’!’;

int b = 7;

float c = 3.7;

double d = 1.5;

printf("%c | %d | %f | %lf | %c \n", a, b, c, d, a);

scanf("%lf", &d);

Remember that %f is for floats, %lf is for doubles

• For printf(), doubles can be implicitly converted to floats

printf("%f\n", &d);

printf("%lf\n", &d);

scanf("%lf", &d);

Programming with C (CSCI 112) Spring 2015 27 / 42

Page 28: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Assignment Statements

An assignment statement stores a value in a variable.

• The value assigned can be the result of another computation.

kms = KMS_PER_MILE * miles;

The above assigns a value (content) to the variable kms.

The value assigned in this case is the result of the multiplication ofthe constant KMS PER MILE by the variable miles.

We should interpret an assignment statement: value = expressionas: value ← expression

This should be read as “becomes”, “gets”, or “takes the value of”rather than “equals”.

Programming with C (CSCI 112) Spring 2015 28 / 42

Page 29: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Assignment Statements

Effect of kms = KMS PER MILE * miles;

Programming with C (CSCI 112) Spring 2015 29 / 42

Page 30: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Assignment Statements

“=” is NOT an algebraic operator. Consider the following:

sum = sum + item;

This is obviously not a correct algebraic equation (if item 6= 0).

This statement instructs the computer to add the current value ofsum to the value of item. Afterward the result is stored back intosum.

Equality:To test for equality, use the “==” operator.Be sure to keep these concepts separate.

Remember!Every variable has contents, even before assignment.

Programming with C (CSCI 112) Spring 2015 30 / 42

Page 31: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Assignment Statements

Effect of sum = sum + item;

Programming with C (CSCI 112) Spring 2015 31 / 42

Page 32: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Arithmetic Operators

Operator Meaning Examples+ addition 5 + 2 = 7

5.0 + 2.0 = 7.0

− subtraction 5 −2 = 35.0 −2.0 = 3.0

* multiplication 5 * 2 = 105.0 * 2.0 = 10.0

/ division 5.0 / 2.0 = 2.55 / 2 = 2

% remainder (mod) 5 % 2 = 15 / 2 = 2

Programming with C (CSCI 112) Spring 2015 32 / 42

Page 33: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Expression Example

Area of a Circle

a = πr2

can be written in C as:

area = PI * radius * radius;

where PI is a constant macro set to 3.14159.

Programming with C (CSCI 112) Spring 2015 33 / 42

Page 34: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Expression Evaluation

Programming with C (CSCI 112) Spring 2015 34 / 42

Page 35: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Expression Example 3

Evaluation Tree and Evaluation for v = (p2 - p1) / (t2 -

t1);

Programming with C (CSCI 112) Spring 2015 35 / 42

Page 36: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Expression Example 4

Evaluation Tree and Evaluation for z - (a + b / 2) + w * -y;

Programming with C (CSCI 112) Spring 2015 36 / 42

Page 37: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

The “return” statement

In your main() function, the return statement will transfer controlfrom your program to the operating system.

“return(0);” returns a 0 to the operating system, which indicatesthat the program executed without error.

• This means that the end of the program was reached.

• It does not mean that the program did what it was supposedto do. There still may have been logical errors.

Other functions also have return statements, which can returnerror codes, data, or nothing at all.

Programming with C (CSCI 112) Spring 2015 37 / 42

Page 38: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Punctuation & Special Symbols

Semicolons: ;Mark the end of a statement (which may take more than one line).

Curly Braces: { }Mark the beginning and end of the body of a function.

Mathematical Symbols: *,/,+,-Are mainly used to compute numeric values.Note that some have additional meaning.In particular, we will talk about * later.

Programming with C (CSCI 112) Spring 2015 38 / 42

Page 39: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Reserved Words

A reserved word is a word that has special meaning to C and cannot be used for other purposes.

These are words that C reserves for its own uses. They are oftennecessary for the compiler to analyze the language’s grammar andto understand what the programmer wants to do (declaringvariables, controlling data flow, etc).

• In example, you cannot have a variable named “return” or“if”.

Reserved words are always lowercase.

See your book or the reference links on the website for a completelist of reserved words.

Programming with C (CSCI 112) Spring 2015 39 / 42

Page 40: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Standard Identifiers

An identifier is a name given to a variable or an operation.

• This is just a formal term for function names and variablenames.

A standard identifier is an identifier that is defined in thestandard C libraries and has special meaning in this standard (suchas ANSI C).

• Examples include printf and scanf

• Unlike reserved words, you can re-define a standard identifier

• It is not recommended to use standard identifiers in anon-standard way, especially when linking to other code thatuses these standards.

Programming with C (CSCI 112) Spring 2015 40 / 42

Page 41: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

User Defined Identifiers

Variables:We choose our own identifiers to name memory cells that will holddata.

Functions:We choose our own identifiers to name operations that we define.

Common Rules for Naming Identifiers:

• May consist only of letters, digits, and underscores

• cannot begin with a digit

• reserved words cannot be used

• standard identifiers should not be redefined

Valid Identifers: var1, inches, KM PER MILEInvalid Identifiers: 1var, the*var, return

Programming with C (CSCI 112) Spring 2015 41 / 42

Page 42: Overview of a C Program - Programming with Cagata.gruza/slides/03-C...Details on formatting codes can be found in the handout. Programming with C (CSCI 112) Spring 2015 25 / 42 Executable

Identifier Naming Guidelines

Some compilers only recognize the first 31 characters of identifiernames, so avoid long identifiers.

Compilers are case-sensitive.

• Aviod very similar names (differ by case, or a single letter)

• ITEM is different than Item is different than item

• Note that conventional C code uses lowercase and underscoresfor variables (as opposed to camel-case used in Java)◦ miles◦ vehicle speed

Constants and Macros usually use all uppercase◦ KMS PER MILE is a defined constant

Choose meaningful identifiers that are easily understood.

• distance = velocity * time is more intelligible than x = y * z.

Programming with C (CSCI 112) Spring 2015 42 / 42