Overview of a C Program Programming with C CSCI 112, Spring 2015 - - PowerPoint PPT Presentation

overview of a c program
SMART_READER_LITE
LIVE PREVIEW

Overview of a C Program Programming with C CSCI 112, Spring 2015 - - PowerPoint PPT Presentation

Overview of a C Program Programming with C CSCI 112, Spring 2015 Patrick Donnelly Montana State University C Language Components Preprocessor Directives Comments The main function Variable Declarations and Data Types


slide-1
SLIDE 1

Overview of a C Program

Programming with C

CSCI 112, Spring 2015

Patrick Donnelly

Montana State University

slide-2
SLIDE 2

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

slide-3
SLIDE 3

General Outline of a C Program

preprocessor directives main function heading { declarations executable statements }

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

slide-4
SLIDE 4

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

slide-5
SLIDE 5

Anatomy of a C Program

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

slide-6
SLIDE 6

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

slide-7
SLIDE 7

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

slide-8
SLIDE 8

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

slide-9
SLIDE 9

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

slide-10
SLIDE 10

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

slide-11
SLIDE 11

Preprocessor Directives

Definition: Preprocessor Directives

Preprocessor Directives are commands that give instructions to the C preprocessor.

Definition: Preprocessor

The Preprocessor is a program that modifies your C program before it is compiled. Preprocessor Directives start with a “#” symbol.

  • #include
  • #define
  • #if
  • #else
  • #endif
  • #pragma

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

slide-12
SLIDE 12

#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 and

scanf library functions.

  • “#include <stdio.h>” inserts their definitions into your

program before compilation.

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

slide-13
SLIDE 13

#define

The #define directive instructs the preprocessor to replace every

  • ccurance of a particular text with a given constant value. The

replacement occurs before compilation. Your source code:

#d e f i n e PI 3.14159 #d e f i n e EULERS NUMBER 2.71828 i n t main ( void ) { double x = 5 ∗ PI ; double y = EULERS NUMBER ∗ 7 ; r e t u r n ( 0 ) ; }

What actually gets compiled:

i n t main ( void ) { double x = 5 ∗ 3.14159; double y = 2.71828 ∗ 7 ; r e t u r n ( 0 ) ; } Programming with C (CSCI 112) Spring 2015 13 / 42

slide-14
SLIDE 14

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

slide-15
SLIDE 15

Comments

Comments provide extra information, making it easier for humans to 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 other programmers 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

slide-16
SLIDE 16

The “main” function

The heading “int main(void)” marks the beginning of the main function where your program execution begins. Every C program has a main function. Braces/Curly brackets: { } mark the beginning and end of the body of the function. A function body has two parts:

  • declarations: (names of variables and data types) tell the

compiler what memory cells are needed in the function and how they should be processed.

  • executable statements: they reflect “actions” of your
  • algorithm. These are translated into machine language by the

compiler and later executed.

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

slide-17
SLIDE 17

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 actual

address in memory). Variable declaration: Statement that communicates to the compiler the names of variables in the program and the data type they represent. Example:

double miles;

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

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

slide-18
SLIDE 18

Numeric Data Types

Definition: Data Type

Data Type: a set of values and a set of operations that can be performed 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 and doubles.

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

slide-19
SLIDE 19

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, doubles and chars.

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

slide-20
SLIDE 20

ASCII Code

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

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

slide-21
SLIDE 21

Executable Statements

Executable Statements: C statements used to write or code the algorithm. The C compiler translates the executable statements into machine code. Examples:

  • Input/Output Operations and Functions
  • printf function
  • scanf function
  • Assignment Statement (=)
  • return Statement/Operation

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

slide-22
SLIDE 22

Executable Statements: Input/Output Operations

Input operation: data transfer from outside the program into computer 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 the program user. Results can be printed to:

  • The standard console output
  • An external file

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

slide-23
SLIDE 23

Executable Statements: Functions

A function takes input parameters and produces an output. A function definition specifies the return type, the input parameters, and the body. A function call is used to call or activate a function.

  • Calling a function means asking another piece of code to do

some work for you.

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

slide-24
SLIDE 24

Executable Statements: Functions - printf()

By calling the printf() function, we are asking for the function to print to standard output. The first argument to printf is the formatting code (in string form), and all following arguments are the the variables to be used in the placeholders.

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

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

slide-25
SLIDE 25

Executable Statements: Functions - printf()

Multiple placeholders can be specified, and the corresponding arguments are then provided in order. Different types of variables require 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

slide-26
SLIDE 26

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 data will be received (%d, %c, %lf), and the following arguments are the variables that will receive the data.

double miles; scanf("%lf", &miles );

The “&” is the address operator in C. The “&” operator in front

  • f variable miles informs the scanf() function about the location
  • f variable miles in the computer’s memory.

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

slide-27
SLIDE 27

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

slide-28
SLIDE 28

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 of the constant KMS PER MILE by the variable miles. We should interpret an assignment statement: value = expression as: 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

slide-29
SLIDE 29

Assignment Statements

Effect of kms = KMS PER MILE * miles;

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

slide-30
SLIDE 30

Assignment Statements

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

sum = sum + item;

This is obviously not a correct algebraic equation (if item = 0). This statement instructs the computer to add the current value of sum to the value of item. Afterward the result is stored back into sum. 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

slide-31
SLIDE 31

Assignment Statements

Effect of sum = sum + item;

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

slide-32
SLIDE 32

Arithmetic Operators

Operator Meaning Examples + addition 5 + 2 = 7 5.0 + 2.0 = 7.0 − subtraction 5 −2 = 3 5.0 −2.0 = 3.0 * multiplication 5 * 2 = 10 5.0 * 2.0 = 10.0 / division 5.0 / 2.0 = 2.5 5 / 2 = 2 % remainder (mod) 5 % 2 = 1 5 / 2 = 2

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

slide-33
SLIDE 33

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

slide-34
SLIDE 34

Expression Evaluation

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

slide-35
SLIDE 35

Expression Example 3

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

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

slide-36
SLIDE 36

Expression Example 4

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

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

slide-37
SLIDE 37

The “return” statement

In your main() function, the return statement will transfer control from your program to the operating system. “return(0);” returns a 0 to the operating system, which indicates that 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 supposed

to do. There still may have been logical errors. Other functions also have return statements, which can return error codes, data, or nothing at all.

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

slide-38
SLIDE 38

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

slide-39
SLIDE 39

Reserved Words

A reserved word is a word that has special meaning to C and can not be used for other purposes. These are words that C reserves for its own uses. They are often necessary for the compiler to analyze the language’s grammar and to understand what the programmer wants to do (declaring variables, 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 complete list of reserved words.

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

slide-40
SLIDE 40

Standard Identifiers

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

  • This is just a formal term for function names and variable

names. A standard identifier is an identifier that is defined in the standard C libraries and has special meaning in this standard (such as 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 a

non-standard way, especially when linking to other code that uses these standards.

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

slide-41
SLIDE 41

User Defined Identifiers

Variables: We choose our own identifiers to name memory cells that will hold data. 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 MILE Invalid Identifiers: 1var, the*var, return

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

slide-42
SLIDE 42

Identifier Naming Guidelines

Some compilers only recognize the first 31 characters of identifier names, 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 underscores

for 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