overview of the c programming language

84
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Overview of the c Programming Language An Overview of the C/C++ Programming Languages

Upload: stephen-hunter

Post on 30-Dec-2015

37 views

Category:

Documents


6 download

DESCRIPTION

An Overview of the C/C++ Programming Languages. Overview of the c Programming Language. What you MUST know before we start:. Overview of the c Programming Language. Not Much : This is the exception to the rule that everything builds on the previous topics. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Overview of the c Programming Language

Page 1

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

An Overview of the C/C++ Programming Languages

Page 2: Overview of the c Programming Language

Page 2

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

What you What you MUSTMUST know before we start: know before we start:

• How to declare variables/Request Memory locations

• How to assign values to variables/set the appropriate bit-sequence in RAM

• We also know all about:• Bits and Bytes (Machine Architecture)• Basic Data Types (Storage in RAM)

• Not Much: This is the exception to the rule that everything builds on the previous topics

• We do know a little about C/C++ Programming:

• NOW we need to learn how to operationalize our knowledege

Page 3: Overview of the c Programming Language

Page 3

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The C Programming LanguageThe C Programming Language

• Developed in 1978 at Bell Labs by Kernighan & Ritchie after A & B failed

• Associated with UNIX • Developed on UNIX Systems • UNIX and its software are written in c• Intended as general purpose Language• Basically a primitive language: 34 (28 original) Key words:

auto break case char const continue

default do double else enum extern

float for gotoifintlong

register

return short

while signed

sizeof static struct switch typedef

union unsigned void volatile

new

release

Page 4: Overview of the c Programming Language

Page 4

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The C++ Programming LanguageThe C++ Programming Language

• Developed by  Bjarne Sroustrup  at Bell Labs during 1983-1985.

and and_eq asm bitand bitor catch class const_cast continue

default delete dynamic_cast explicit export falsefriendinlinemutable

namespace not not_eq operator or or_eq private protected public

reinterpret_cast template this throw true

• C++ is an extension of C. • Prior to 1983, Stroustrup added features to C

and formed what he called "C with Classes". • In 1983 the use of classes and object-oriented features with the

power and efficiency of C. The term C++ was first used in 1983.

• Additional C++ Reserved Words

try typeid typename using

virtual wchar_t xor xor_eq

40 Additional; 74 Total

Page 5: Overview of the c Programming Language

Page 5

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

So, master of insipidness, which language will we So, master of insipidness, which language will we use ???use ???

• Mostly simple (?) C• Most of C++ consists of CMost of C++ consists of C• You really can’t understand C++ unless you know C You really can’t understand C++ unless you know C

firstfirst

• We will use some C++ commands• Mostly for I/O activitiesMostly for I/O activities

• You will learn more about C++ in later classes

Page 6: Overview of the c Programming Language

Page 6

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

So, insipidness personified, is there anything we So, insipidness personified, is there anything we should look out for ???should look out for ???

• As Stroustrup remarked (I’m paraphrasing):

In C, it is easy to shoot yourself in In C, it is easy to shoot yourself in the foot. In C++, if you do, you the foot. In C++, if you do, you will blow your foot off.will blow your foot off.

Ouch!!! No es bueno!!Ouch!!! No es bueno!!

No es bueno para nada !!!No es bueno para nada !!!

Page 7: Overview of the c Programming Language

Page 7

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

C/C++ OperatorsC/C++ OperatorsStandard/Common Operators:

Binary Operators: Operators Between Two Operands:

Operator+

Meaning Example Definition.Addition x = 6 + 2; Add the values on either side of +

- Subtraction x = 6 - 2; Subtract right value from left value

* Multiplication x = 6 * 2; Subtract right hand side values/ Division x = 6/2; Divide left value by right value

% Modulus x = 6 % 2; Remainder of left divided by right

What about exponentiation??? Either x = 6 ^ 2 OR x = 6 ** 2 ???What about exponentiation??? Either x = 6 ^ 2 OR x = 6 ** 2 ???

NOTE:NOTE: Dividing real numbers yields EXACT resultsDividing Integers yields TRUNCATED results

No Such Thing: You must write your own function (Or use an available one)

Page 8: Overview of the c Programming Language

Page 8

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Assignment OperatorsAssignment Operators: Assigning Values to RAM:

Operator

=

Example

x = 6 + 2;

Definition.

Location x will get the value 6 + 2 ( = 8)+= x += 3 Same as x = x + 3: IFIF x contained the

value 4, it now contains the value 7

Same as x = x - 3: IFIF x contained the value 4, it now contains the value 1

= x = 3

*= x *= 3 Same as x = x * 3: IFIF x contained the value 4, it now contains the value 12

/= x /= 3 Same as x = x / 3: IFIF x contained the value 4: IFIF x is a float (real), it now contains 1.33 IFIF x is an integer, it now contains the value 1

%= x %= 3 Same as x = x % 3: IFIF x contained the value 4, it now contains the value 1 (3 goes into 4 Once with ONEONE left over)

Page 9: Overview of the c Programming Language

Page 9

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Unary OperatorsUnary Operators: Operators on a single Operand:Operator

-

Meaning

Minus Sign

Example

x = -2;

Definition.

Assign a negative value+ Plus Sign x = +2; Assign a Positive value

++ Increment x = ++y; Prefix Notation OROR x = y++; Postfix Notation

-- Decrement x = --y; Prefix Notation OROR x = y--; Postfix Notation

Prefix and Postfix Notation?? What’s that all About ???Prefix and Postfix Notation?? What’s that all About ???

int x,y,a,b; a = b = 1; // Initialize the variables (locations) with the value 1 x = 2 * ++a; // PREFIX Notation: First increment a by 1 (a = 2) // Then Multiply by 2 & assign to x (x=2*2) y = 2 * b++; // POSTFIX Notation: First multiply b by 2 & assign to y (y=1*2)

// Then increment b by 1 (b = 2) printf("%d %d\n",x,y); // The Output would appear as: 4 24 2

Consider the following section of c code:

Page 10: Overview of the c Programming Language

Page 10

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

There are two (2) Additional Unary Operators:There are two (2) Additional Unary Operators:

sizeofsizeof Return the size of the operand (in bytes)

int i = 12; float f = -123.45;printf("%d sizeof = %d\n",i,sizeof i); // would produce: 12 sizeof = 2printf("%7.2f sizeof = %d\n",f,sizeof f); // would produce: -123.45 sizeof = 4

Consider the following section of c code:

(type)(type) Convert a value to the specified data type

int a = 4; float b = 12.245;printf("%d %ld\n",a,(long) a); // would produce: 4 4printf("%d %f\n",a,(float) a); // would produce: 4 4.000000printf("%f %d\n",b,(int) b); } // would produce: 12.245000 12

Consider the following section of c code:

Page 11: Overview of the c Programming Language

Page 11

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Relational OperatorsRelational Operators: Operators on two Operands Yielding a T/F Answer:Operator Meaning Example Definition.

< Less Than x < 2; False if x contains the value 2

<= Less Than OR Equal To

x <= 2; True if x contains the value 2

== Equal To x = = 2; True if x contains the value 2

! = Not Equal To x ! = 2; False if x contains the value 2

> Greater than x > 2; False if x contains the value 2

>= Greater than OR Equal To

x >= 2; True if x contains the value 2

&& And x > 2 && x < 4

False if x contains the value 2

| | Or x = = 2 | | x = = 4

True if x contains the value 2

! Not ! (x = = 2) False if x contains the value 2

Page 12: Overview of the c Programming Language

Page 12

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Order of Operations:Order of Operations:

Order

1Operator( )

2 + - ++ -- (unary) ! (Rel)3 * / %4 + - (binary)5 < > <= >=6 == !=

9 =

Given: int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8;What is the value of the statement:

a = (a * ((b + c) % d) / e) - (f * g + 6) * h / 4 + 1;

| | 8

&&7

Page 13: Overview of the c Programming Language

Page 13

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

a = (a * ((b + c) % d) / e) - (f * g + 6) * h / 4 + 1;

Given: int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8;

2 + 3 = 55 6 * 7 = 42

42 + 6 = 485 % 4 = 1

1 * 1 = 1

1 / 5 = 0 48 * 8 = 384

384 / 4 = 96

0 - 96 = - 96

- 96 + 1 = - 95- 95

Page 14: Overview of the c Programming Language

Page 14

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Example 2: Given: int a = 1, b = 2, c = 3, d = 4, e = 5, f = 6, g = 7, h = 8;

Evaluate:

++a * b-- + c % d / e - f-- * g + 6 * h++ / b + h;

2

2 * 2 = 4 3 % 4 = 3

3 / 5 = 0 6 * 7 = 42 6 * 8 = 48

48 / 2 = 24

4 + 0 = 4

4 - 42 = - 38

- 38 + 24 = - 14

- 14 + 8 = - 6- 6

Note that now: a = 2, b = 1, f = 5, h = 9

Page 15: Overview of the c Programming Language

Page 15

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Example 3: Given: int a = 1, b = 2, c = 3, d = 4;Consider the statement:

a > b || b < c && c == 3 || d < 4 && b != c

False True FalseTrue True

True False

True

True

Page 16: Overview of the c Programming Language

Page 16

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Printing in C: Printing in C: • No Input/Output facilities are provided

• There are no reserved keywords for READ or WRITE• Functions such as scanf, printf, cout scanf, printf, cout andand cin cin must be

added:

#include <stdio.h>#include <stdio.h> // a C // a C pre-compilerpre-compiler directive directive

Why?? Aren’t these standard functions??Why?? Aren’t these standard functions??

Yes, but the designers of C/C++ left I/O implementation Yes, but the designers of C/C++ left I/O implementation up to compiler writers so that they could better match up to compiler writers so that they could better match input and output to specific machinesinput and output to specific machines

#include <iostream.h>#include <iostream.h> // a C++ // a C++ pre-compilerpre-compiler directive directive

Page 17: Overview of the c Programming Language

Page 17

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Conversion specifiers for scanfscanf and printfprintf:

Specifier(s) Output %c Single Character%d %i Signed decimal Integer

%f Signed floating-point, decimal notation

Example B457

-6.576%e %E Signed floating-point, e or E notation -4.5e3 2.1E-2%g %G Use shorter or %f or %e (%f or %E) -2.1 4.56E4

%o Unsigned octal notation 4271

%u 7832Unsigned decimal Integer%ld %lu Signed/Unsigned long Integer

%Lf %Le Long double floating-pt (also %LE) 7.32 -6.1e4

-345 64

%x %X Unsigned hexadecimal notation 4d2a F6B%s Character string Hello%p Pointer (address) 4FF0: 8BC1%% Print a % sign %

Additional information about printf/scanf specifiers can be found in the Supplementary Materials Link

Page 18: Overview of the c Programming Language

Page 18

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Misusing Print SpecifiersMisusing Print Specifiers

Assume the following C declarations:int a = -32, b = 6781;int a = -32, b = 6781;unsigned int c = 49216;unsigned int c = 49216;long d = -53212;long d = -53212;unsigned long e = 123456;unsigned long e = 123456;

What would happen if we applied the following print specifier?

printf("%8d %8d %8d %8d %8d\n", a, b, c, d, e);printf("%8d %8d %8d %8d %8d\n", a, b, c, d, e);

The following output would be produced:⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞-32-32 ⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞67816781 ⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞-16320-16320 ⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞1232412324 ⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞⃞-1-1

Page 19: Overview of the c Programming Language

Page 19

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Why??Why??Some are easy to understand. Consider the declarationunsigned int c = 49216; unsigned int c = 49216; and how it would be stored in RAM:

4921610 = 1100000001000000 (On 16-bits)

Since we told the compiler to print the value as a signed int:

Negative Sign 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0

Add 1 (2’s Compliment): Compliment: 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1

+ 1

0 1 1 1 1 1 1 1 1 0 0 0 0 0 0

= 213 + 212 + 211 + 210 + 29 + 28 + 27 + 26

= 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 = -16,320

Page 20: Overview of the c Programming Language

Page 20

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Some are a little more complex. Consider the declaration

long d = -53212; long d = -53212; and how it would be stored in RAM:

5321210 = 00000000000000001100111111011100 (32-bits)

-5321210 = 11111111111111110011000000100011 (1’s Comp)+ 1

11111111111111110011000000100100 (2’s Comp)

Taking the right-most 16-bits:

= 213 + 212 + 25 + 22

= 8,192 + 4,096 + 32 + 4

= 12,324 (As it appeared in the output)

Page 21: Overview of the c Programming Language

Page 21

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Other Misuses of Print SpecifiersOther Misuses of Print Specifiers

Sometimes, we can misuse conversion specifiers and get lucky.We can ALWAYS represent characters as integers (since they are stored as integers on 8-bits).

Consider the declaration: char c1 = ‘C’, c2 = 51;char c1 = ‘C’, c2 = 51;And the statement: printf(“%c %d %c %d”, c1, c1, c2, c2);printf(“%c %d %c %d”, c1, c1, c2, c2);

The output would be: C 67 3 51C 67 3 51

SOMETIMES, we can also print integers as characters:

Given: int i1 = ‘C’, i2 = 51;int i1 = ‘C’, i2 = 51;

printf(“%c %d %c %d”, i1, i1, i2, i2);printf(“%c %d %c %d”, i1, i1, i2, i2);

The output would be: C 67 3 51C 67 3 51

Page 22: Overview of the c Programming Language

Page 22

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

SOMETIMES, even though we can appear to print integers as characters, we will get strange results:

Given: int i = 318;int i = 318;printf(“%c %d”, i, i);printf(“%c %d”, i, i);

The output would be: > 318> 318

Why???Why???Once again, consider how the value is stored in RAM:

31810 = 0000000100111110 (On 16-bits)

Taking the right-most 8-bits:

= 25 + 24 + 23 + 22 + 21

= 32 + 16 + 8 + 4 + 2 = 6262

Which is the ASCII value for the character >

Page 23: Overview of the c Programming Language

Page 23

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Generally speaking, it is best to avoid misusing specifiers:Given: int a = 317;int a = 317;

long b = 53212;long b = 53212;float c = 43.672;float c = 43.672;long double d = 5.6E7;long double d = 5.6E7;

The statement: printf(“%d %ld %12.4f %13.4Lf”,a , a, a, a);printf(“%d %ld %12.4f %13.4Lf”,a , a, a, a);

Would Yield: -317 -317 106233539 0.0000 -0.0000 106233539 0.0000 -0.0000

The statement: printf(“%d %ld %12.4f %13.4Lf”,b , b, b, b);printf(“%d %ld %12.4f %13.4Lf”,b , b, b, b);Would Yield: -12324 -12324 5321253212 0.0000 0.0000 0.0000 0.0000

The statement: printf(“%d %ld %12.4f %13.4Lf”,c , c, c, c);printf(“%d %ld %12.4f %13.4Lf”,c , c, c, c);Would Yield: 0 536870912 0 536870912 43.672043.6720 0.0000 0.0000

The statement: printf(“%d %ld %12.4f %13.4Lf”,d , d, d, d);printf(“%d %ld %12.4f %13.4Lf”,d , d, d, d);Would Yield: 0 0 -2.8220783e+1040 0 -2.8220783e+104 56000000.000056000000.0000

Page 24: Overview of the c Programming Language

Page 24

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

What if I need to print a data type using a (different) specifier?Don’t forget the typetype (unary) operator. Using our previous

variable declarations, we could print them out on different format.

The statement: printf(“%ld %12.4f”, (long) a , (float) a);printf(“%ld %12.4f”, (long) a , (float) a);Would Yield: -317 -317.0000-317 -317.0000

The statement: printf(“%d %ld”,(int) c , (long) c);printf(“%d %ld”,(int) c , (long) c);

43 4343 43Would Yield:

The statement: printf(“%d %12.4f”, (int) b , (float) b);printf(“%d %12.4f”, (int) b , (float) b);Would Yield: -12324 53212.0000-12324 53212.0000

Given: int a = 317; long b = 53212; float c = 43.672;int a = 317; long b = 53212; float c = 43.672;

??? Casting variable ??? Casting variable bb as as int int yields yields -12324-12324 when when b = 53212b = 53212 ??? ???

Page 25: Overview of the c Programming Language

Page 25

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

5321210 = 00000000000000001100111111011100 (32-bits)

Taking the right-most 16-bits:

= (-) 213 + 212 + 25 + 22

= (-) 8,192 + 4,096 + 32 + 4 = -12,324 (As it appeared in the output)

Remember how long d = 53212; long d = 53212; would be stored in RAM:

The number transferred is:Which Equals:

Negative Compliment 011000000100011

1100111111011100

1’s Compliment

+ 1011000000100100

Page 26: Overview of the c Programming Language

Page 26

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Printing in C++: Printing in C++: • Printing in C++ is actually much easier than C.• Once you have declared a variable (location), the cout command

will automatically print using the specified data type.

#include <iostream.h> //Notice that this is the C++ header filevoid main(){

char c = 109;int i = -765;float f = 2.0445;cout << "c = " << c << " i = " << i << " f = " << f << endl;

}

• The code:

• Produces the output:

Page 27: Overview of the c Programming Language

Page 27

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Well This is a Well This is a LOTLOT easier than C !! easier than C !!Why didn’t you show us this before ???Why didn’t you show us this before ???

No pain, no gain --No pain, no gain --

So tell me, oh master of sadism, does this mean So tell me, oh master of sadism, does this mean that you can’t specify how you want the output to that you can’t specify how you want the output to

be displayed, as you can in C ??be displayed, as you can in C ??

Non, mon ami --Non, mon ami --

Additional information about cout and cin (the equivalent of scanf in C) specifiers can be found in the Supplementary Materials Link

Page 28: Overview of the c Programming Language

Page 28

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

One C++ which is much more convenient, and we will use, is the cin command

• This command will get user input from the keyboard and store it in a variable location

• It is similar to the scanf command in C, but much neater

• As we will see when we discuss Character Arrays (Strings), the command is actually doing a lot

• There may be some problems, however, so be careful with this command

Page 29: Overview of the c Programming Language

Page 29

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The Program below:

Produces the Output

Page 30: Overview of the c Programming Language

Page 30

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The Basic Structure of the C Programming LanguageThe Basic Structure of the C Programming Language

• Precompiler Instructions: #include <iostream.h>#include <iostream.h> #define ZERO 0#define ZERO 0 (function prototypes) (external variables)

Additional code/shorthand/ definitions

(data type) main main (arguments) { // begin{ // begin declarations statements (return value) }} // end // end

• Main Function:

A C program consists of one or more function. The primary function MUST be labeled mainmain

function 1function 1

function nfunction n

• Additional Functions:(optional) functions arethe building blocks of C

Page 31: Overview of the c Programming Language

Page 31

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

C/C++ Programming Conventions:C/C++ Programming Conventions:

• Case Sensitive: UPPERCASE vs. lowercase• NOT Strongly typed: Checking left to Programmer• Each Statement ends with a semicolon• Elipses and Parentheses MUST match: {…. } ( …. ) • C is a translated language (vs. interpreted):

Source CodeSource Code

CompilerCompiler

Object CodeObject Code

Executable CodeExecutable Code

LinkerLinker

Library CodeLibrary Code

Start-up CodeStart-up Code

Page 32: Overview of the c Programming Language

Page 32

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Precompiler DirectivesPrecompiler Directives

#include #include <<header files>header files> <stdio.h><stdio.h> e.g., fore.g., for printf()printf() <stdlib.h><stdlib.h> e.g., fore.g., for atoi()atoi()

“ “user-defined functions” user-defined functions” e.g., e.g., “myfunction.h”“myfunction.h”<string.h><string.h> e.g., fore.g., for strcmp()strcmp()

#define #define User Defined Constant PI 3.15149PI 3.15149 Replace the expression PIPI with 3.151493.15149 where ever it occurs in the program.

Given: float area, r;float area, r; . . . . .

Should a statement such as: area = PI * (r * r);area = PI * (r * r); occur

It would be replaced with: area =3.15249* (r * r);area =3.15249* (r * r); where ever it occurs

Page 33: Overview of the c Programming Language

Page 33

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Precompiler Directives (Continued)Precompiler Directives (Continued)

#define #define User Defined Macro SQUARE (x) (x * x)SQUARE (x) (x * x)

Once again, Given: float area, r;float area, r; . . . . .

Should the statement: area = PI * SQUARE(r);area = PI * SQUARE(r); occur, it would be replaced with: area = 3.15149 * (r * r); area = 3.15149 * (r * r); throughout the program

Additional Precompiler InstructionsAdditional Precompiler Instructions

(function prototypes) to be discussed laterto be discussed later

(external variables) to be discussed laterto be discussed later

Page 34: Overview of the c Programming Language

Page 34

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Example Usage of Precompiler DirectivesExample Usage of Precompiler Directives

#include <stdio.h>#include <stdio.h> // Needed for printf// Needed for printf#define PI 3.14159#define PI 3.14159 // Pi estimation// Pi estimation#define SQUARE(x) (x*x)#define SQUARE(x) (x*x) // a value squared// a value squaredint main()int main() // main statement// main statement{{ // begin the function// begin the function float area, r = 4.5;float area, r = 4.5; // declare variables// declare variables area = PI * SQUARE(r);area = PI * SQUARE(r); // calculate area// calculate area printf("The area of the circle is: %7.3f\n",area);printf("The area of the circle is: %7.3f\n",area); return(0);return(0); // return an // return an intint value value}} // end the function// end the function

Which would print out:The area of the circle is: 63.617The area of the circle is: 63.617

Since: 4.5 * 4.5 = 20.25 * 4.5 * 4.5 = 20.25 * 3.141593.14159 = 63.6171975 = 63.6171975

Page 35: Overview of the c Programming Language

Page 35

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Substitution of a Macro in a Program:Substitution of a Macro in a Program:

#include <stdio.h>#include <stdio.h> // Needed for printf// Needed for printf#define PI 3.14159#define PI 3.14159 // Pi estimation// Pi estimation#define SQUARE(x) (x*x)#define SQUARE(x) (x*x) // a value squared// a value squaredint main()int main() // main statement// main statement{{ // begin the function// begin the function float area, r = 4.5;float area, r = 4.5; // declare variables// declare variables area = 3.14159 * (r * r);area = 3.14159 * (r * r); // calculate area// calculate area printf("The area of the circle is: %7.3f\n",area);printf("The area of the circle is: %7.3f\n",area); return(0);return(0); // return an // return an intint value value}} // end the function// end the function

Unlike functions, Macros are substituted throughout the code

Page 36: Overview of the c Programming Language

Page 36

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The The mainmain function function

• MUST be labeled main main

• May return any standard data type:• char mainchar main Returns a character • int mainint main Returns an integer value• float mainfloat main Returns a real number

• Or need not return a value: • void mainvoid main Returns a void value

• May receive arguments (parameters) of any type: • int main (int argc, char argv)int main (int argc, char argv)

• But usually does NOT: • int main (void)int main (void) • void main ()void main ()

Page 37: Overview of the c Programming Language

Page 37

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Characteristics of ALL functionsCharacteristics of ALL functions

• MUST Begin with beginbegin character { { and end with endend character } }

void main ()void main (){{ . . . .. . . . }}

• Generally (although not always) start with variable declarations

void main ()void main (){ char c = ‘B’;{ char c = ‘B’; // initialize 1-byte of RAM with 66// initialize 1-byte of RAM with 66 int i = 0, j;int i = 0, j; // initialize 2-bytes of RAM with 0// initialize 2-bytes of RAM with 0

// reserve additional 2-bytes for j// reserve additional 2-bytes for j float real1, real2 = -32.45;float real1, real2 = -32.45; // reserve 4-bytes of RAM for real1// reserve 4-bytes of RAM for real1 // initialize 4-bytes RAM with -32.45// initialize 4-bytes RAM with -32.45 . . . .. . . . }}

Declarations may be made ANYWHERE in the function

Page 38: Overview of the c Programming Language

Page 38

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Characteristics of ALL functions (continued)Characteristics of ALL functions (continued)• Generally (although not always) contain a variable number of statements and control statements:

void main ()void main (){ { . . . .. . . . x = . . .x = . . . if . . .if . . . for . . .for . . . while . . .while . . . printf . . .printf . . . . . . .. . . . }}

These statements will be discussed later{

• Should (unless void) return an appropriate value

int main ()int main (){{ . . . .. . . . return (0);return (0); // if NOT included, results in a // if NOT included, results in a warningwarning }}

Page 39: Overview of the c Programming Language

Page 39

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

ifif Statements Statements

• Branching Statement: Junction at which the program has choice of two paths to follow.

#include <stdio.h>#include <stdio.h>void main ()void main (){ { char ch = ‘B’;char ch = ‘B’; if (ch % 2 == 0)if (ch % 2 == 0) printf (“The number is even\n”);printf (“The number is even\n”);}}

Which would yield: The number is evenThe number is evenSince the ASCII value for ‘B’ is 66

Note that if we had initialized: char ch = ‘A’char ch = ‘A’; or char ch = ‘C’;char ch = ‘C’;Nothing would have been printed since the ASCII value for ‘A’ is 65 and the ASCII value of ‘C’ is 67.

• ALWAYS based on a TRUE/FALSE condition

Page 40: Overview of the c Programming Language

Page 40

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Multi-lineMulti-line ifif Statements Statements

• IF more than one statement is to be executed in am if statement, begin and end elipses must be included:

#include <stdio.h>#include <stdio.h>void main ()void main (){ { char ch = ‘B’;char ch = ‘B’; if (ch % 2 == 0)if (ch % 2 == 0) { printf (“The number is even\n”);{ printf (“The number is even\n”); ch++;ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch);printf (“The new character is %c (or ASCII %d)\n”, ch, ch); }}}}

Which would yield: The number is evenThe number is evenThe new character is C (or ASCII 67)The new character is C (or ASCII 67)

Page 41: Overview of the c Programming Language

Page 41

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

• OMISSION of the elipses, given the following code, would yield:

#include <stdio.h>#include <stdio.h>void main ()void main (){ { char ch = ‘C’;char ch = ‘C’; // NOTICE the ASCII value of C is 67 (odd)// NOTICE the ASCII value of C is 67 (odd) if (ch % 2 == 0)if (ch % 2 == 0) printf (“The number is even\n”);printf (“The number is even\n”); ch++;ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch);printf (“The new character is %c (or ASCII %d)\n”, ch, ch);}}

Which would yield: The new character is D (or ASCII 68)The new character is D (or ASCII 68)

Page 42: Overview of the c Programming Language

Page 42

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

CompoundCompound if elseif else Statements Statements

#include <stdio.h>#include <stdio.h>void main ()void main (){ { char ch = ‘B’;char ch = ‘B’; if (ch % 2 == 0)if (ch % 2 == 0) printf (“The number is even\n”);printf (“The number is even\n”); elseelse printf (“The number is odd\n”);printf (“The number is odd\n”);}}

Which would yield: The number is evenThe number is evenHowever, the code:#include <stdio.h>#include <stdio.h>void main ()void main (){ { char ch = ‘C’;char ch = ‘C’; if (ch % 2 == 0)if (ch % 2 == 0) printf (“The number is even\n”);printf (“The number is even\n”); elseelse printf (“The number is odd\n”);printf (“The number is odd\n”);}}

Would yield: The number is oddThe number is odd

Page 43: Overview of the c Programming Language

Page 43

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

• NOTE that multi-line statements still require elipses:{ { char ch = ‘B’; // char ch = ‘B’; // include include and and void main()void main() omitted to save space omitted to save space if (ch % 2 == 0)if (ch % 2 == 0) { printf (“The number is even\n”);{ printf (“The number is even\n”); ch++;ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch);printf (“The new character is %c (or ASCII %d)\n”, ch, ch); }} elseelse printf (“The number is odd\n”);printf (“The number is odd\n”);}}

Would yield: The number is evenThe number is evenThe new character is C (or ASCII 67)The new character is C (or ASCII 67)

While:

{ { char ch = ‘C’; // char ch = ‘C’; // include include and and void main()void main() omitted to save space omitted to save space if (ch % 2 == 0)if (ch % 2 == 0) printf (“The number is even\n”);printf (“The number is even\n”); ch++;ch++; printf (“The new character is %c (or ASCII %d)\n”, ch, ch);printf (“The new character is %c (or ASCII %d)\n”, ch, ch); elseelse printf (“The number is odd\n”);printf (“The number is odd\n”);}}

Would yield AN ERROR MESSAGE (misplaced else)

Page 44: Overview of the c Programming Language

Page 44

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

AdditionalAdditional if elseif else Statements StatementsSuppose we wished to determine if a letter is a vowel or consonant:

• a, e, i, o, u (accept y): The letter is a vowel• Otherwise: It is a consonant

#include <stdio.h>#include <stdio.h>void main ()void main (){ { char letter = ‘u’;char letter = ‘u’; // The letter we wish to classify// The letter we wish to classify if if ((letter == ‘a’) || (letter == ‘e’) || (letter == ‘i’) ||((letter == ‘a’) || (letter == ‘e’) || (letter == ‘i’) || (letter == ‘o’) || (letter == ‘u’) || (letter == ‘y’))(letter == ‘o’) || (letter == ‘u’) || (letter == ‘y’)) printf (“The letter is a vowel\n”);printf (“The letter is a vowel\n”); elseelse printf (“The letter is a consonant\n”);printf (“The letter is a consonant\n”);}}

Which would yield: The letter is a vowelThe letter is a vowel

All of the OR operators make the statement confusing, however

Page 45: Overview of the c Programming Language

Page 45

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

We COULD rewrite the program as:

#include <stdio.h>#include <stdio.h>void main ()void main (){ { char letter = ‘u’;char letter = ‘u’; // The letter we wish to classify// The letter we wish to classify if (letter == ‘a’)if (letter == ‘a’) printf (“The letter is a vowel\n”);printf (“The letter is a vowel\n”); elseelse if (letter == ‘e’)if (letter == ‘e’)

printf (“The letter is a vowel\n”);printf (“The letter is a vowel\n”); elseelse if (letter == ‘i’)if (letter == ‘i’)

printf (“The letter is a vowel\n”);printf (“The letter is a vowel\n”); elseelse if (letter == ‘o’)if (letter == ‘o’)

printf (“The letter is a vowel\n”);printf (“The letter is a vowel\n”); elseelse if (letter == ‘u’)if (letter == ‘u’)

printf (“The letter is a vowel\n”);printf (“The letter is a vowel\n”); elseelse

printf (“The letter is a consonant\n”);printf (“The letter is a consonant\n”);}}

Page 46: Overview of the c Programming Language

Page 46

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

• The previous program uses compound if elseif else statements or uses nestednested if elseif else statements• NOTICE: each elseelse MUST have a corresponding ifif statement preceding it• If there are too many statements, the program can become ‘messy’

Alternative:#include <stdio.h>#include <stdio.h>void main ()void main (){ { char letter = ‘u’;char letter = ‘u’; // The letter we wish to classify// The letter we wish to classify switchswitch { case ‘a’ : printf (“The letter is a vowel\n”);{ case ‘a’ : printf (“The letter is a vowel\n”); break;break; case ‘e’ : printf (“The letter is a vowel\n”);case ‘e’ : printf (“The letter is a vowel\n”); break;break; case ‘i’ : printf (“The letter is a vowel\n”);case ‘i’ : printf (“The letter is a vowel\n”); break;break; case ‘o’ : printf (“The letter is a vowel\n”);case ‘o’ : printf (“The letter is a vowel\n”); break;break; case ‘u’ : printf (“The letter is a vowel\n”);case ‘u’ : printf (“The letter is a vowel\n”); break;break; default : printf(“The letter is a consonant\n”);default : printf(“The letter is a consonant\n”); }}}}

Page 47: Overview of the c Programming Language

Page 47

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

forfor Statement Statement

• A ‘Looping’ statement: Repetition of statements within • Similar to a PERFORM WHILEPERFORM WHILE statement in COBOL• Repeats statements UNTIL a set condition is met• Consists of three (3) components:

INITIALIZATIONINITIALIZATION: Set initial values

CONDITION TO CHECKCONDITION TO CHECK:

Evaluate to either TRUE TRUE or FALSEFALSE While TRUETRUE: CONTINUE When FALSEFALSE: STOP

UPDATINGUPDATING: Resetting of values

for( ; ; )for( ; ; )

Page 48: Overview of the c Programming Language

Page 48

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Assume we wished to print out the squares of 1 through 3:

#include <stdio.h>#include <stdio.h>void main ()void main (){ { int i;int i; for (i = 1; i < 4; i++)for (i = 1; i < 4; i++)

/* the initial value of /* the initial value of ii is 1 is 1 continue while the value of continue while the value of ii is 3 or less is 3 or less increment increment ii by one until it is less than 4 */ by one until it is less than 4 */

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i); } }

The Output would be:The Output would be:

The Square of 1 is 1The Square of 1 is 1The Square of 2 is 4The Square of 2 is 4The Square of 3 is 9The Square of 3 is 9

Page 49: Overview of the c Programming Language

Page 49

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

How does this really work???How does this really work???

Let’s take it line by line:

int i;int i; Requests 2-bytes of contiguous storageLet’s assume at location 6450 in RAM

6450 6451

0 0 1 1 0 1 0 1 0 1 0 1 0 0 0 1Contents Unknown

for (i = 1; i < 4; i++)for (i = 1; i < 4; i++)

INITIALIZATION: Performed ONLY One Time

Set the CONTENTS of location ii to 1:

6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1

Page 50: Overview of the c Programming Language

Page 50

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Condition Check 1:

Are the contents of ii < 4 ??? 6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1Yes: Perform Statement

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output:1 * 1 = 1

The Square ofThe Square of 11 isis 11

Update #1:

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Increment the contents of location ii by 1

6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

ii contains 2

Page 51: Overview of the c Programming Language

Page 51

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Condition Check 2:

Are the contents of ii < 4 ??? 6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0Yes: Perform Statement

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output:2 * 2 = 4

The Square ofThe Square of 22 isis 44

Update #2:

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Increment the contents of location ii by 1

6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

ii contains 3

Page 52: Overview of the c Programming Language

Page 52

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Condition Check 3:

Are the contents of ii < 4 ??? 6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1Yes: Perform Statement

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output:3 * 3 = 9

The Square ofThe Square of 33 isis 99

Update #3:

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Increment the contents of location ii by 1

6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

ii contains 4

Page 53: Overview of the c Programming Language

Page 53

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

for (i = 1; i < 4; i++) for (i = 1; i < 4; i++)

Condition Check 4:

Are the contents of ii < 4 ??? 6450 6451

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0NO: End of loop

Next Statement ??

}} End of Program

Alternatives to the for for loop:

• whilewhile (condition) (condition) statement: • ENTRY Condition Loop • Loop entered into ONLY if the condition is TRUE• do { … } whiledo { … } while (condition); (condition); statement: • EXIT Condition Loop • Loop Repeated ONLY if the condition is TRUE

Page 54: Overview of the c Programming Language

Page 54

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Consider the while (condition)while (condition) program (which also prints out the squares of 1 through 3):

#include <stdio.h>#include <stdio.h>void main ()void main (){ { int i = 1;int i = 1;

/* Notice that we need to initialize the value of location /* Notice that we need to initialize the value of location ii BEFORE we enter the loopBEFORE we enter the loop */ */

while (i <= 3)while (i <= 3) {{ printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i); i++;i++; }} } }

The Output (again) would be:The Output (again) would be:

The Square of 1 is 1The Square of 1 is 1The Square of 2 is 4The Square of 2 is 4The Square of 3 is 9The Square of 3 is 9

Page 55: Overview of the c Programming Language

Page 55

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

How does this program work???How does this program work???Let’s (again) take it line by line:

int i = 1;int i = 1; Requests 2-bytes of storage & set in the value 1Let’s assume at location 72250 in RAM

72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1while (i <= 3)while (i <= 3)

Are the contents of ii <= 3 ??

Yes: Begin the Loop

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output: The Square ofThe Square of 11

{{

isis 11

1 * 1 = 1

i++;i++; 72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

Increment ii

ii contains the value 2}}

Page 56: Overview of the c Programming Language

Page 56

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

while (i <= 3)while (i <= 3)

Are the contents of ii <= 3 ??

Yes: Begin the Loop

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output: The Square ofThe Square of 22

{{

isis 44

2 * 2 = 4

i++;i++; 72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

Increment ii

ii contains the value 3}}

Condition Check #2:

Page 57: Overview of the c Programming Language

Page 57

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

while (i <= 3)while (i <= 3)

Are the contents of ii <= 3 ??

Yes: Begin the Loop

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output: The Square ofThe Square of 33

{{

isis 99

3 * 3 = 9

i++;i++; 72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

Increment ii

ii contains the value 4}}

Condition Check #3:

Page 58: Overview of the c Programming Language

Page 58

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0

while (i <= 3)while (i <= 3)

Are the contents of ii <= 3 ??

NO: Exit the loop

Condition Check #4:

A do { … } whiledo { … } while (condition); (condition); statement is similar EXCEPT that the condition is checked AT THE END of the loop

Consider the program:{ { int i = 4;int i = 4; // The top 2 lines are omitted to save space // The top 2 lines are omitted to save space

/* Notice that the contents of I are set to 4 and the loop should/* Notice that the contents of I are set to 4 and the loop should NOT be entered */NOT be entered */

dodo {{ printf (“The Square of %d is %d\n”, i, i * i); printf (“The Square of %d is %d\n”, i, i * i); i++;i++; } while (i <= 3);} while (i <= 3); } }

Page 59: Overview of the c Programming Language

Page 59

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Let’s (once again) take it line by line:

int i = 4;int i = 4; Requests 2-bytes of storage & set in the value 4Let’s assume at location 72250 in RAM

72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0dodo Begin the Loop

printf (“The Square of %d is %d\n”, i, i * i);printf (“The Square of %d is %d\n”, i, i * i);

Output: The Square ofThe Square of 44

{{

isis 1616

4 * 4 = 16

i++;i++; 72250 72251

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1

Increment ii

ii contains the value 5

} while (i <= 3);} while (i <= 3);

Since the value contained in location ii is greater than 3: STOP

Page 60: Overview of the c Programming Language

Page 60

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

FunctionsFunctions

• A self contained unit of code • Intended to perform a specific task • Cause an operation to be performed (e.g., printf()printf()) • Return a value (e.g., fopen()fopen(), return the address of a file)• Benefits: • Avoid repetitive code • Promote modularity

• Readability • Easier editing

Consider a function to perform exponentiation (let’s call it powerpower)(Remember: C does not have an exponentiation operator)

Page 61: Overview of the c Programming Language

Page 61

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

#include <stdio.h>#include <stdio.h>int power(int number, int exponent);int power(int number, int exponent); // function PROTOTYPE// function PROTOTYPEvoid main ()void main (){ { int i, j, result;int i, j, result; for (i = 2; i < 4; i++)for (i = 2; i < 4; i++) for (j = 2; j < 4; ++j)for (j = 2; j < 4; ++j) { result = power(i, j);{ result = power(i, j); // call function power // call function power printf (“The Number %d Raised to %d is %d\n”, printf (“The Number %d Raised to %d is %d\n”, i, j, result);i, j, result); }} } }

int power (int number, int exponent) // Same as prototype int power (int number, int exponent) // Same as prototype { int i, value = number;{ int i, value = number; // EXCEPT w/o semicolon // EXCEPT w/o semicolon

for (i = 2; i <= exponent; i++)for (i = 2; i <= exponent; i++) value = value * number;value = value * number; return (value);return (value);}}

Page 62: Overview of the c Programming Language

Page 62

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

How does this program work???How does this program work???Let’s take it line by line:

int power(int number, int exponent);int power(int number, int exponent);

The function PROTOTYPE lets the compiler know :

1. The Name of the function being called (powerpower)

2. The Number & type of data which will be passed to the function (i.e., there are 2 integers being passed)

3. The type of data which will be Returned by the function

• The actual function MUST appear as it does in the prototype EXCEPT that it will NOT have a semicolon at the end

(in this case, an integer)

• Failure to include the prototype will cause an error:FUNCTION SHOULD HAVE A PROTOTYPE

Page 63: Overview of the c Programming Language

Page 63

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

int i, j, result;int i, j, result; Requests a total of 6-bytes:2 for ii, 2 for j j, And 2 for result result

for (i = 2; i < 4; i++)for (i = 2; i < 4; i++)

2250 2251

0 0 0 1 0 0 0 0 0 1 1 1 0 1 0 0 2252 2253

0 1 1 1 0 1 0 0 0 0 1 1 0 1 1 1 2254 2255

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2256 2257

1 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0

2250 2251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

Initialize ii with 2

Contents ofLocation iiless than 4 ??

Yes: Enter Loop

Page 64: Overview of the c Programming Language

Page 64

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

2252 (jj) 2253

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0for (j = 2; j < 4; ++j)for (j = 2; j < 4; ++j)

Initialize location jj

Contents of jj less than 4?? Yes: Continue{ result = power( i, j );{ result = power( i, j );

int power (int number, int exponent)int power (int number, int exponent)

call function powerpowerMove the contents of ii Move the contents of jj

2250 (ii) 2251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

2262 (numbernumber) 2263

2264 (exponentexponent) 2265

To location numbernumber

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

NOTE: This is a DIFFERENT address

To location exponentexponent

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

Page 65: Overview of the c Programming Language

Page 65

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

{ int i, value = number;{ int i, value = number;

2268 (ii) 2269

0 0 0 1 0 1 0 0 0 1 1 1 0 1 0 0 2270 (valuevalue) 2271

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

Set aside 2-bytes of storage(at location ii)

NOTE:NOTE: Even though we have called our variable ii, AND we have already declared a variable ii (in function mainmain) THEY ARE NOTNOT THE SAME VARIABLES (The addresses are DIFFERENTDIFFERENT)

Set aside an additional 2-bytes(location valuevalue) AND initializewith the contents of locationnumbernumber (i.e., 2)

Page 66: Overview of the c Programming Language

Page 66

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

If we were to look inside RAM at this point, we might see:

2250 & 2251 (variable ii: function mainmain)

2

2252 & 2253 (variable jj: function mainmain)

22256 & 2257 (resultresult: function mainmain)

Undefined

2254 & 2255

Unused or in Use2258 & 2259

Unused or in Use

2260 & 2261

Unused or in Use2262 & 2263 (numbernumber: function powerpower)

2

2264 & 2265 (exponentexponent: function powerpower)

22266 & 2267

Unused or in Use2270 & 2271 (valuevalue: function powerpower)

2

2268 & 2269 ( variable ii: function powerpower)

Undefined2264 & 2265

Unused or in Use

Page 67: Overview of the c Programming Language

Page 67

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Continuing our example:

for (i = 2; i <= exponent; i++)for (i = 2; i <= exponent; i++)Set location ii to 2

2268 & 2269 ( variable ii: function powerpower)

2

location ii less or equal to location exponentexponent (2) ?? YES: Continue

value = value * number;value = value * number;

2270 & 2271 (value)value)

2 *

2262 & 2263 (numbernumber)

2

2270 & 2271 (valuevalue)

4

Page 68: Overview of the c Programming Language

Page 68

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Update #1:

for (i = 2; i <= exponent; i++)for (i = 2; i <= exponent; i++)

Increment the contents of location ii by 1

2268 & 2269 ( variable ii: function powerpower)

3Check #2:

location ii less or equal to location exponentexponent (2) ??

NO: STOP

Next Statementreturn (value);return (value);

Pass the contents of location valuevalue 2270 & 2271 (valuevalue)

4to the calling function (mainmain)

Page 69: Overview of the c Programming Language

Page 69

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Before the return, let’s once again look inside RAM::

2250 & 2251 (variable ii: function mainmain)

2

2252 & 2253 (variable jj: function mainmain)

22256 & 2257 (resultresult: function mainmain)

Undefined

2254 & 2255

Unused or in Use2258 & 2259

Unused or in Use

2260 & 2261

Unused or in Use2262 & 2263 (numbernumber: function powerpower)

2

2264 & 2265 (exponentexponent: function powerpower)

22266 & 2267

Unused or in Use2270 & 2271 (valuevalue: function powerpower)

4

2268 & 2269 ( variable ii: function powerpower)

32264 & 2265

Unused or in Use

Page 70: Overview of the c Programming Language

Page 70

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The contents of location valuevalue are now returned:

{ result = power( i, j );{ result = power( i, j );

Returns:

2270 & 2271 (value: value: from functionfrom function power power)

4

Assign to location resultresult 2256 & 2257 (resultresult: function mainmain)

4The next Statement:

printf (“The Number %d Raised to %d is %d\n”, i, j,result);printf (“The Number %d Raised to %d is %d\n”, i, j,result);

Results in the output:

}}

The Number 2 Raised to 2 is 4The Number 2 Raised to 2 is 4

Page 71: Overview of the c Programming Language

Page 71

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Before continuing, let’s again look inside RAM

2250 & 2251 (variable ii: function mainmain)

2

2252 & 2253 (variable jj: function mainmain)

22256 & 2257 (resultresult: function mainmain)

4

2254 & 2255

Unused or in Use2258 & 2259

Unused or in Use

2260 & 2261

Unused or in Use2262 & 2263

MEMORY AVAILABLE

2264 & 2265

MEMORY AVAILABLE

2266 & 2267

Unused or in Use2270 & 2271)

MEMORY AVAILABLE

2268 & 2269

MEMORY AVAILABLE

2264 & 2265

Unused or in Use

Page 72: Overview of the c Programming Language

Page 72

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Why is the memory required for functionWhy is the memory required for function power power now available ??now available ??• Memory allocations are made each time a function is called• When a function returns, allocations are freed

• The next time the function is called, different (or the same, depending on what is available at the time) memory allocations are made

Does that mean that if we multiple function calls, the Does that mean that if we multiple function calls, the same RAM allocations can be used ??same RAM allocations can be used ?? YesYes

A major advantage of functions is that the RAM allocated can be reused with each call

Page 73: Overview of the c Programming Language

Page 73

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

2252 (jj) 2253

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1for (j = 2; j < 4; ++j)for (j = 2; j < 4; ++j)

Contents of jj less than 4?? Yes: Continue{ result = power( i, j );{ result = power( i, j );

int power (int number, int exponent)int power (int number, int exponent)

call function powerpowerMove the contents of ii Move the contents of jj

2250 (ii) 2251

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

2260 (numbernumber) 2261

2262 (exponentexponent) 2263

To location numbernumber

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

NOTE: The address is DIFFERENT than before

To location exponentexponent

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

Continuing: increment(jj = 3)

Page 74: Overview of the c Programming Language

Page 74

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

{ int i, value = number;{ int i, value = number;

2264 (ii) 2265

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2268 (valuevalue) 2269

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

Set aside 2-bytes of storage (at location ii)

Set aside 2-bytes (location valuevalue) & initialize with the contents of location numbernumber (i.e., 2)

Note that address 2264 contains its previous value

for (i = 2; i <= exponent; i++)for (i = 2; i <= exponent; i++)

ii <= 3 ?? Yes: Continue

value = value * number;value = value * number;

2268 & 2269 (value)value)

2

2262 & 2263 (number)number)

2*

2268 & 2269 (value)value)

4

Page 75: Overview of the c Programming Language

Page 75

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

for (i = 2; i <= exponent; i++)for (i = 2; i <= exponent; i++)

Yes: Continuevalue = value * number;value = value * number;

2268 & 2269 (value)value)

4

2262 & 2263 (number)number)

2*

2268 & 2269 (value)value)

8

2264 (ii) 2265

0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1

Increment ii ((ii = 3)

ii <= 3 ??

for (i = 2; i <= exponent; i++)for (i = 2; i <= exponent; i++)

2264 & 2265 (i)i)

4

Increment ii

ii <= 3 ??

NO: End LoopNext Statementreturn (value);return (value);

Page 76: Overview of the c Programming Language

Page 76

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Before the return, let’s once again look inside RAM::

2250 & 2251 (variable ii: function mainmain)

2

2252 & 2253 (variable jj: function mainmain)

32256 & 2257 (resultresult: function mainmain)

4

2254 & 2255

Unused or in Use2258 & 2259

Unused or in Use

2260 & 2261 (numbernumber: function powerpower)

22262 & 2263 (exponentexponent: function powerpower)

3

2264 & 2265 (ii: function powerpower)

42266 & 2267

Unused or in Use

2268 & 2269 (valuevalue: function powerpower)

8

Notice again that RAM assignments may vary with each call

Page 77: Overview of the c Programming Language

Page 77

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

The contents of location valuevalue are now returned:

{ result = power( i, j );{ result = power( i, j );

Returns:

2268 & 2269 (value: value: from functionfrom function power power)

8

Assign to location resultresult 2256 & 2257 (resultresult: function mainmain)

8The next Statement:

printf (“The Number %d Raised to %d is %d\n”, i, j, result);printf (“The Number %d Raised to %d is %d\n”, i, j, result);

Results in the output:

}}

The Number 2 Raised to 3 is 8The Number 2 Raised to 3 is 8

Page 78: Overview of the c Programming Language

Page 78

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Once again, if we were to now look inside RAM (upon return):

2250 & 2251 (variable ii: function mainmain)

2

2252 & 2253 (variable jj: function mainmain)

32256 & 2257 (resultresult: function mainmain)

8

2254 & 2255

Unused or in Use2258 & 2259

Unused or in Use

2260 & 2261

MEMORY AVAILABLE

2262 & 2263

MEMORY AVAILABLE

2264 & 2265

MEMORY AVAILABLE

2266 & 2267

Unused or in Use2270 & 2271)

Unused or in Use

2268 & 2269

MEMORY AVAILABLE

2264 & 2265

Unused or in Use

Page 79: Overview of the c Programming Language

Page 79

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

2252 (jj) 2253

0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0for (j = 2; j < 4; ++j)for (j = 2; j < 4; ++j)

Contents of jj less than 4?? NO: End Loop

Now: increment(jj = 4)

The program now increments the value of ii (in main main):

for (i = 2; i < 4; i++)for (i = 2; i < 4; i++)2250 & 2251 (ii: function mainmain)

3

And the program repeats the above procedures one more time, producing the output:

The Number 3 Raised to 2 is 9The Number 3 Raised to 2 is 9The Number 3 Raised to 3 is 27The Number 3 Raised to 3 is 27

Page 80: Overview of the c Programming Language

Page 80

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

Will the Memory Allocations made by a function Will the Memory Allocations made by a function ALWAYSALWAYS be freed upon return??? be freed upon return??? YESYES

Variables, when declared inside a function, are locallocal or automaticautomatic:

• They exist ONLY for the duration of the call

What if I wish to access the same variables from any function What if I wish to access the same variables from any function in the program?in the program?

There are globalglobal or externalexternal variables which:• Are declared outside of a function (before mainmain)• Can be accesses, and modified, by any function in the program • Exist as long as the program runs

Let’s rewrite our function powerpower using global variables:

Page 81: Overview of the c Programming Language

Page 81

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

#include <stdio.h>#include <stdio.h>int power();int power(); // function PROTOTYPE// function PROTOTYPEint i, j, result;int i, j, result; // GLOBAL variables// GLOBAL variables

void main ()void main (){ for (i = 2; i < 4; i++){ for (i = 2; i < 4; i++) for (j = 2; j < 4; ++j)for (j = 2; j < 4; ++j) { result = power(i, j);{ result = power(i, j); // call function power// call function power printf (“The Number %d Raised to %d is %d\n”, i, ,j, result);printf (“The Number %d Raised to %d is %d\n”, i, ,j, result); }} } }

int power () int power () // Same as prototype // Same as prototype { int counter, value = i;{ int counter, value = i;

for (counter = 2; counter <= j; counter++)for (counter = 2; counter <= j; counter++) value = value * number;value = value * number;}}

Page 82: Overview of the c Programming Language

Page 82

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

That is much easier !!!That is much easier !!!

Maybe – but is considered bad formMaybe – but is considered bad form

So you would penalize us if we use global So you would penalize us if we use global variables in our program ????variables in our program ????

YesYes

I bet you like torturing small animals also !!I bet you like torturing small animals also !!

Page 83: Overview of the c Programming Language

Page 83

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language

So what do we need to do ??So what do we need to do ??• All the standard C/C++ operators and the order of operations• All the C/C++ relational operators and the order of operations• The basic structure of the languages• Basic I/O (C++ is OK)

• Using functions

• To finish the 2nd programming assignment

??? Any Questions ??? (Please!!)??? Any Questions ??? (Please!!)

• If Statements• Iteration (for and while)

Gee, that’s all, oh driver of slaves ??Gee, that’s all, oh driver of slaves ??• No – Don’t forget:

• To submit your programming questions and references

• To get started on the 3rd programming assignment

Page 84: Overview of the c Programming Language

Page 84

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Overview of the c Programming Language