+ All Categories
Home > Education > C Programming by Süleyman Kondakci

C Programming by Süleyman Kondakci

Date post: 28-Jan-2015
Category:
Upload: sueleyman-kondakci
View: 120 times
Download: 3 times
Share this document with a friend
Description:
A general coverage of the C language is presented. These slides are useful for students attending C courses at universities and other institutions as well as others following C tutorials or learning the language by themselves. Comments are welcome for creating better future. Faculty of Eng. & Computer Sciences of IEU, Izmir-Turkey, Assoc. Prof. Dr. S. Kondakci
Popular Tags:
167
Composed for Composed for SE 115 C programming SE 115 C programming Faculty of Engineering & Faculty of Engineering & Computer Sciences Computer Sciences Izmir University of Economics Izmir University of Economics Assoc. Prof. Dr. Süleyman Kondakci [email protected] http://homes.ieu.edu.tr/skondakci
Transcript
Page 1: C Programming by Süleyman Kondakci

Composed for Composed for

SE 115 C programmingSE 115 C programmingFaculty of Engineering & Faculty of Engineering &

Computer Sciences Computer Sciences

Izmir University of EconomicsIzmir University of Economics

Assoc. Prof. Dr. Süleyman Kondakci

[email protected]

http://homes.ieu.edu.tr/skondakci

Page 2: C Programming by Süleyman Kondakci

Summary of C Operations• Arithmetic:

• int i = i+1; i++; i--; i *= 2;

• +, -, *, /, %,

• Relational and Logical:• <, >, <=, >=, ==, !=

• &&, ||, &, |, !

• Flow Control:• if ( ) { } else { }

• while ( ) { }

• do { } while ( );

• for(i=1; i <= 100; i++) { }

• switch ( ) {case 1: … }

• continue; break;

Page 3: C Programming by Süleyman Kondakci

Relational,equality, and logical operatorsRelational,equality, and logical operators

Less than: <

Greater than: >

Less than or equal: <=

Greater than or equal: >=

Relational Operator:

Page 4: C Programming by Süleyman Kondakci

Equality and Logical OperatorsEquality and Logical Operators

Equality Operators:

Equal: ==

Not equal: !=

Logical Operators:

Negation: !

Logical and: &&

Logical or: ||

Page 5: C Programming by Süleyman Kondakci

Example: Conditional OperatorsExample: Conditional Operators

int x=0, y=10, w=20, z, T=1, F=0;

z = (x == 0); /*** logical operator; re sult --> 0 or 1 ***/

z = (x = 0); /*** assignment operator; result --> ***/

z = (x == 1);

z = (x = 15);

z = (x != 2);

z = (x < 10);

z = (x <= 50);

z = ((x=y) < 10); /*** performs assignment, comp ares with 10 ***/

z = (x==5 && y<15);

z = (x==5 && y>5 && w==10);

z = (x==5 || y>5 && w==10);

z = (T && T && F && x && x); /*** ==> F; ***/

z = (F || T || x || x); /*** ==> T; ***/

/*** value of x doesn't matter ***/

Page 6: C Programming by Süleyman Kondakci

Input to & Output From Program Input to & Output From Program

Input: scanf ("format specifier", variable)

Output: printf ("format specifier", variable)

Format specifiers

%c = as a character

%d = as a decimal integer

%e = as a floating-point number in scientififc notation

%f = as a floating-point number

%g = in the e-format or f-format, whichever is shor ter

%s = as a string of characters

Page 7: C Programming by Süleyman Kondakci

Small Sample ProgramsSmall Sample Programs

/*hello.c - traditional zeroth program*/#include <stdio.h>

int main(){

printf( " Hello world!\n");return 0;

}

Hello world!

On the screen

Page 8: C Programming by Süleyman Kondakci

Escape SequencesEscape Sequences

\a bell

\t horizontal tab

\' single quote

\n newline

\r carriage return

\b backspace

\v vertical tab

\" double quote

\? question mark

\f formfeed

\\ backslash

\ooo octal number

\xhhhexadecimal number

Escaped characters produce visual and audible effects

Page 9: C Programming by Süleyman Kondakci

The Output Function (printf)The Output Function (printf)

Character

Argument Type; Printed As

d, I int ; decimal number

o int ; unsigned octal number (without a leading zero)

x, Xint ; unsigned hexadecimal number (without a leading Ox or OX, usingabcdef or ABCDEFfor 10,...,15)

u int ; unsigned decimal number

c int ; single character

schar; print characters from the string until a '\0' or the number of charachters given by the precision

f double; [-]m.dddddd, where the number of d's is given by the precision (default is 6)

e, Edouble; [-]m.dddddde ±xxor [-]m.ddddddE ±xxwhere the number of d's is given by the precision (default is 6)

g, Gdouble; use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f; trailing zeros and a trailing decimal point are not printed

p void * ; pointer (implementation-dependent representation)

% no argument is converted; print a %

Page 10: C Programming by Süleyman Kondakci

The Input Function (scanf)The Input Function (scanf)

Character

Input Data; Argument Type

d decimal integer; int *

Iinteger; int * ; the integer may be in octal (leading 0) or hexadecimal (leading 0x or 0X)

o octal intger (with or without leading zero); int *

u unsigned decimal integer; unsigned int *

x hexadecimal number (with or without a leading 0x or 0X); int *

ccharacters; char *. The next input characters (default 1) are placed at the indicated spot. The normal skip over white space is suppressed; to read the next non-white space character, use %1s

scharacter string (not quoted); char * ; pointing to an array of characters large enough for the string and a terminating `\0' that will be added

e, f, gfloating-point number with optional sign, optional decimal point, and optional exponent; float *

% literal %; no assignment is made

Page 11: C Programming by Süleyman Kondakci

A Very Tiny ProgramA Very Tiny Program

/*fahr.c (several versions) - convert Fahrenheit to Celsius. Originally not mine, SK*/

int main(){int fahr = 42, cels;cels = 5*(fahr-32)/9;printf("%d degrees Fahrenheit is %d degrees

Celsius\n", fahr, cels);return 0;}

Page 12: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 13: C Programming by Süleyman Kondakci

The if StatementThe if Statement

if( expression 1)

statement 1;

else if ( expression 2)

statement 2;

else statement 3

The if statement has two forms:1) Plain if:

Page 14: C Programming by Süleyman Kondakci

Nested if StatementNested if Statement

if (expression) {if (expression) {if (expression) {if (expression) {

if (expression) {if (expression) {if (expression) {if (expression) {

statements statements statements statements

if (expression) { if (expression) { if (expression) { if (expression) {

statementsstatementsstatementsstatements

}}}}

}}}}

} else {} else {} else {} else {

statementsstatementsstatementsstatements

}}}}

2) Nested if:

Page 15: C Programming by Süleyman Kondakci

The The ?? :: decision decision operatoroperatorss

expression1?expression2: expression3

Same as

if(expression1) expression2

else expression3

Page 16: C Programming by Süleyman Kondakci

Example: Example: The The ?? and and :: operatoroperatorss

X = 12;

y = (x < 5) ? 5 : 10;

Gives the same result as this

if (x < 5) y = 5;

else

y = 10;

Page 17: C Programming by Süleyman Kondakci

C Language Blocks and StylingC Language Blocks and Styling

{

Statements

}

{

{

... {

}

}

}

inner block

outer block

single block

Multiple nested block structure

Page 18: C Programming by Süleyman Kondakci

Example: Single BlockExample: Single Block

for (i=0; i<=10; i++) {

printf("index is: %d", i);

}

if (a == b && a <= c || c >0)

printf("Aha!! \a\a");

You can aslo write like this:

if (a == b && a <= c || c >0)

{

printf("Aha!!\a\a");

}

Or

if (a == b && a <= c || c >0) printf("Aha!!\a\a");

Page 19: C Programming by Süleyman Kondakci

Example: Multiple (nested) BlocksExample: Multiple (nested) Blocks

int a=2; int b=30; int c=11;if(a==b){

if( b<=c && c >10){c= a -b;while (a <=10) {

printf("Value of a: %d", a);B = a*c;

}a = a -1;}

}else{printf("That is all folks!");

}

Page 20: C Programming by Süleyman Kondakci

Small Sample ProgramsSmall Sample Programs

/* Uses scanf() to get input. Originally not mine, S.K *//* Uses printf() to display the result. */#include <stdio.h>int main() {

int fahr, cels;printf("How many degrees? ");scanf("%d", &fahr);cels = 5*(fahr-32)/9;printf("%d degrees Fahrenheit is %d degrees Celsius \ n",

fahr, cels);return 0;}

Page 21: C Programming by Süleyman Kondakci

Small Sample ProgramsSmall Sample Programs

/*same, but with real numbers instead of silly inte gers*/#include <tdio.h>int main() {

double fahr, cels;printf("How many degrees? ");scanf("%lf", &fahr);cels = 5.0*(fahr-32.0)/9.0;printf("%.2f degrees Fahrenheit is %.2f degrees

Celsius\n", fahr, cels);return 0;}

Page 22: C Programming by Süleyman Kondakci

Modified Farhrenheit to CModified Farhrenheit to C--11

/*fahrcels.c (several versions) - use a conditional statement to select one of

two calculations.*/#include <stdio.h>int main() {

double fahr, cels;int unit; /*'C' for Celsius input, 'F' for Fahrenheit*/

/*get input type*/printf("Type C to convert Celsius (C) to Fahrenheit (F), or F to C: ");unit = getchar();

/*get input, and do the appropriate conversion*/printf("degrees? ");if(unit == 'C')

{scanf("%lf", &cels);fahr = 9.0*cels/5.0+32.0;} else {scanf("%lf", &fahr);cels = 5.0*(fahr-32.0)/9.0;}

printf("%.3f degrees Fahrenheit is %.3f degrees Celsius\n", fahr, cels);return 0;}

Page 23: C Programming by Süleyman Kondakci

Modified Farhrenheit to CModified Farhrenheit to C--22

/*uses logical OR to equlize lowercase to uppercase characters*/#include <stdio.h>int main(){

double fahr, cels;int unit; /*'C' for Celsius input, 'F' for Fahrenhei t*/

/*get input type*/printf("Type C to convert Celsius to Fahrenheit, or F to C: ");unit = getchar();

/*get input, and do the appropriate conversion*/printf("degrees? ");if((unit == 'C') || (unit == 'c')) {

scanf("%lf", &cels);fahr = 9.0*cels/5.0+32.0;

} else {scanf("%lf", &fahr);cels = 5.0*(fahr-32.0)/9.0;

}printf("%.3f degrees Fahrenheit is %.3f degrees Cel sius\n", fahr,

cels);return 0;}

Page 24: C Programming by Süleyman Kondakci

Modified Farhrenheit to CModified Farhrenheit to C--33

/*uses a conditional expression as well as a condit ional statement*/#include <stdio.h>#include <ctype.h>int main() {

double fahr, cels;int unit; /*'C' for Celsius input, 'F' for Fahrenhei t*/

/*get input type*/printf("Type C to convert Celsius to Fahrenheit, or F to C: ");unit = toupper(getchar());

/*get input, and do the appropriate calculation*/printf("degrees? ");scanf("%lf", (unit=='C')? &cels: &fahr);if(unit == 'C')

fahr = 9.0*cels/5.0+32.0;else

cels = 5.0*(fahr-32.0)/9.0;printf("%.3f degrees Fahrenheit is %.3f degrees Cel sius\n", fahr,

cels);return 0;}

Page 25: C Programming by Süleyman Kondakci

Modified Farhrenheit to CModified Farhrenheit to C--44

#include <stdio.h>#include <ctype.h>int main() {

double fahr, cels;int unit; /*'C' for Celsius input, 'F' for Fahrenhei t*/

/*get input type*/printf("Type C to convert Celsius to Fahrenheit, or F to C: ");unit = toupper(getchar());

/*get input, and do the appropriate calculation*/printf("degrees? ");if(unit == 'C') {

scanf("%lf", &cels);fahr = 9.0*cels/5.0+32.0;

} else {scanf("%lf", &fahr);cels = 5.0*(fahr-32.0)/9.0;

}printf("%.3f degrees Fahrenheit is %.3f degrees Cel sius\n", fahr,

cels);return 0;

}

Page 26: C Programming by Süleyman Kondakci

Real C ProgrammingReal C Programming

Page 27: C Programming by Süleyman Kondakci

The The forfor Loop SyntaxLoop Syntax

for (initialize_loop_counter; check_loop_range; update_loop_counfor (initialize_loop_counter; check_loop_range; update_loop_counfor (initialize_loop_counter; check_loop_range; update_loop_counfor (initialize_loop_counter; check_loop_range; update_loop_counter) {ter) {ter) {ter) {

statementsstatementsstatementsstatements

}}}}

Page 28: C Programming by Süleyman Kondakci

Example: Example: forfor LoopLoop

#include <stdio.h>

#include <stdlib.h>

int main(){

int i;

for(i = 0; i <= 10; i++){

// Inside the loop

printf( " loop count = %d\n", i);

}

// End of the loop

return 0;

}

Page 29: C Programming by Süleyman Kondakci

The The whilewhile Loop SyntaxLoop Syntax

while( expression)

Statement; //Single statement

Or like this if blocks of statements!

while( expression) {

Statements

}

Page 30: C Programming by Süleyman Kondakci

Example: Example: while while LoopLoop

include <stdio.h>

#include <stdlib.h>

int main(){

int inchar;

/* The Classic Bit */

while( (inchar = getchar()) != EOF){

printf("%c You typed:\n", inchar);

}

return 0;

}

Page 31: C Programming by Süleyman Kondakci

The The dodo--whilewhile Loop SyntaxLoop Syntax

First execute then check

do {

statements

}

First check then execute

while ( expression) {

statements

}

Page 32: C Programming by Süleyman Kondakci

Example: Example: forfor and and whilewhile LoopsLoops

#include <stdio.h>

#include <stdlib.h>

int main(){

int i;

for(i = 0; i <= 10; i++){

printf("%d\n", i);

}

return 0;

}

#include <stdio.h>

#include <stdlib.h>

int main(){

int i;

i = 0;

while(i <= 10){

printf("%d\n", i);

i++;

}

return 0;

}

Page 33: C Programming by Süleyman Kondakci

Example: Example: dodo--whilewhile LoopLoop

#include <stdio.h>

#include <stdlib.h>

int main(){

int i; i = 0;

/* check */

do {

printf("%d\n", i);

/* increment i */

i++;

} while(i <= 10);

return 0;

}

Page 34: C Programming by Süleyman Kondakci

The The switchswitch StatementStatement

expressionexpressionexpressionexpression = some_value= some_value= some_value= some_value; /* can be the result of another ; /* can be the result of another ; /* can be the result of another ; /* can be the result of another

expression or a user defined value. */expression or a user defined value. */expression or a user defined value. */expression or a user defined value. */

some_valuesome_valuesome_valuesome_value can be can be can be can be const1, const2,..., const100const1, const2,..., const100const1, const2,..., const100const1, const2,..., const100 or elseor elseor elseor else

switch (switch (switch (switch (expressionexpressionexpressionexpression)))) { { { {

case case case case const1const1const1const1: : : : statementsstatementsstatementsstatements ; break;; break;; break;; break;

case case case case const2const2const2const2: : : : statementsstatementsstatementsstatements ; ; ; ; break;break;break;break;

............

case const100: statements; breakcase const100: statements; breakcase const100: statements; breakcase const100: statements; break

default: default: default: default: statementsstatementsstatementsstatements ; ; ; ; break;break;break;break;

}}}}

Page 35: C Programming by Süleyman Kondakci

Example: Example: switchswitch vs vs ifif StatementStatement

#include <stdio.h>#include <stdlib.h>

int main(){int i; for(i = 0; i <= 3; i++){

switch(i){case 1: printf("1 \n");

break;case 2: printf("2 \n");

break;case 3: printf("3 \n");

break;default:

printf("default\n");break;

}}

return 0;}

#include <stdio.h>#include <stdlib.h>

int main(){int i;

for(i = 0; i <= 3; i++){if (i == 1) printf("1 \n");else if (i == 2) printf("2 \n");else if (== 3) printf("3 \n");else printf("default\n");

}return 0;

}

Page 36: C Programming by Süleyman Kondakci

The The breakbreak statemet: Get out of the loop!statemet: Get out of the loop!

#include <stdio.h>

#include <stdlib.h>

int main(){

int i;

for(i = 0; i < 100000000; i++){

printf("Press s to stop");

if(getchar() == 's')

break;

printf("%d\n", i);

}

return 0;

}

Page 37: C Programming by Süleyman Kondakci

The The continuecontinue Statement: Skip some partsStatement: Skip some parts

#include <stdio.h>

int main(){

int i;

for(i = -10; i < 10; i++){

if(i == 0 || i==6 || i == 9 )

// do not display 0, 6, and 9, continue with others

continue;

printf("%d \n", i);

// Other statements .....

}

return 0;

}

Page 38: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 39: C Programming by Süleyman Kondakci

Functions Functions -- why and how ?why and how ?

•• If a program is too If a program is too

longlong

•• Modularization Modularization ––

easier to easier to

•• codecode

•• debugdebug

•• Code reuseCode reuse

•• Passing Passing

arguments to arguments to

functionsfunctions

–– By valueBy value

–– By referenceBy reference

•• Returning values Returning values

from functionsfrom functions

–– By valueBy value

–– By referenceBy reference

Page 40: C Programming by Süleyman Kondakci

Definition and Usage of FunctionsDefinition and Usage of Functions

#include <stdio.h>#include <stdlib.h>/** function prototype declarations start here**/int add(int a, int b);int GetPosinteger(void); // or just int GetPosinteg er(); /** End of function prototype declarations **/int main(){

int x, y, z;x = GetPosinteger();y = GetPosinteger();printf("%d + %d = %d\n", x, y, add(x,y));return 0;

}int add(int a, int b){

return a+b;}int GetPosinteger(void){

int a;do

{printf("Enter a positive integer: ");scanf("%d", &a);

} while (a <= 0);return a;

}

Page 41: C Programming by Süleyman Kondakci

FunctionsFunctions are subprograms!are subprograms!

The syntax for declaring a function:return-type function-name (argument declarations){

local variable declarationsStatements

}

Signature (or prototype) of a function:return-type function-name (argument list)

Page 42: C Programming by Süleyman Kondakci

VoidVoid in in voidvoid out or out or return valuereturn value

void print_message( void ) // Inputs are void!

{

// Here void means no input parameter and no return value

printf("hello"); // No return

}

int add(int a, int b) // We have two int inputs a & b

{

int sum;

sum = a + b;

return sum; // This is the output (return value)

}

Page 43: C Programming by Süleyman Kondakci

Functions – Call by Value

#include <stdio.h>int sum(int a, int b);

/* function prototype at start of file */

void main(void){int total = sum(4,5); /* call to the function */

printf("The sum of 4 and 5 is %d", total);}

int sum(int a, int b){ /* the function itself - arguments passed by value*/

return (a+b); /* return by value */}

Page 44: C Programming by Süleyman Kondakci

Functions- Call by Reference (later!!)

#include <stdio.h>/* function prototype at start of the code */int sum(int *pa, int *pb); // Pointer references as input

void main(void){int a=4, b=5;int *ptr = &b; int total;total = sum(&a,ptr); /* call to the function */printf("The sum of 4 and 5 is %d", total);

}

int sum(int *pa, int *pb){ /* the function definition here- arguments passed by reference */return (*pa+*pb); /* return by ref */

}

Page 45: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 46: C Programming by Süleyman Kondakci

Making Making MenusMenus for Usersfor Users

void menu (){

printf("The following options\n");printf("R ==> Register a book\n ");printf("D ==> Display data about all books\ n "); printf("F ==> Find and show a book\n "); printf("Enter [R,D,F] or [Q] to Quit: ");

}

Page 47: C Programming by Süleyman Kondakci

Using functions with Using functions with MenuMenu

void main(void){

char opt;menu();opt=getchar();

do {switch (opt) {

case 'r'| R': Register(); break;case 'f'|'F': Find(); break; case 'd'|'D': Show_data(); break;case 'd'|'D': break();default: menu(); opt=getchar();break;

}}while (opt != 'q' && opt != 'Q');

}

Page 48: C Programming by Süleyman Kondakci

Example PseudoExample Pseudo--codecode

# include<# include<# include<# include<stdiostdiostdiostdio.h.h.h.h>>>>

# # # # typedeftypedeftypedeftypedef enumenumenumenum {worse={worse={worse={worse=----1, bad=0, good=1, best=2} credit;1, bad=0, good=1, best=2} credit;1, bad=0, good=1, best=2} credit;1, bad=0, good=1, best=2} credit;

/* Some global constant definitions, if required ... *//* Some global constant definitions, if required ... *//* Some global constant definitions, if required ... *//* Some global constant definitions, if required ... */

/* Start of function /* Start of function /* Start of function /* Start of function defsdefsdefsdefs */*/*/*/

void register();void list();void void register();void list();void void register();void list();void void register();void list();void find_dispfind_dispfind_dispfind_disp();();();();

void delete();void change();int get_option();void delete();void change();int get_option();void delete();void change();int get_option();void delete();void change();int get_option();

// End of function // End of function // End of function // End of function DefsDefsDefsDefs

/* End of function /* End of function /* End of function /* End of function DefsDefsDefsDefs */*/*/*/

/* Start of main(), Action definitions *//* Start of main(), Action definitions *//* Start of main(), Action definitions *//* Start of main(), Action definitions */

int int int int main() {main() {main() {main() {

/* Some local variable and constant /* Some local variable and constant /* Some local variable and constant /* Some local variable and constant defsdefsdefsdefs */*/*/*/

short int opt;short int opt;short int opt;short int opt;

do {do {do {do {

opt=get_option();opt=get_option();opt=get_option();opt=get_option();

switch(opt)switch(opt)switch(opt)switch(opt)

{{{{

case 1: register(); break;case 1: register(); break;case 1: register(); break;case 1: register(); break;

case 2: list(); break;case 2: list(); break;case 2: list(); break;case 2: list(); break;

case 3: case 3: case 3: case 3: find_dispfind_dispfind_dispfind_disp(); break;(); break;(); break;(); break;

case 4: delete(); break;case 4: delete(); break;case 4: delete(); break;case 4: delete(); break;

case 5: change(); break;case 5: change(); break;case 5: change(); break;case 5: change(); break;

case 6: exit(); /* exit the loop, hence the program */case 6: exit(); /* exit the loop, hence the program */case 6: exit(); /* exit the loop, hence the program */case 6: exit(); /* exit the loop, hence the program */

}}}}

} while(1);} while(1);} while(1);} while(1); /* End of while *//* End of while *//* End of while *//* End of while */

return 0;return 0;return 0;return 0;

} /* End of main() */} /* End of main() */} /* End of main() */} /* End of main() */

Page 49: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 50: C Programming by Süleyman Kondakci

RecursionRecursion

Recursion = a function calls itself as a function for unknown times. We call this recursive call

1

1

n

i

s u m i−

=

=∑ for (i = 1 ; i <= n-1; i++) sum++;

int sum(int n) {

if (n <= 1)

return 1

else

return (n + sum(n-1));

}

Recursiveversion

Iterativeversion

Page 51: C Programming by Süleyman Kondakci

Recursive functionRecursive function

int f( int x )

{

if( x == 0 )

return 0;

else

return 2 * f( x - 1 ) + x * x;

}

22 ( 1)f f x x= − +Compute this function

Page 52: C Programming by Süleyman Kondakci

KKth Fibonacci Numbersth Fibonacci Numbers

0 1 1 2

0

1

2 1 0

3 2 1

4 3 2

5 4 3

6 5 4

7 6 5

8 7 6

0 , 1, ,

1

1

1

1 1 1 1 3

1 3 1 1 5

1 5 3 1 9

1 9 5 1 1 5

1 1 5 9 1 2 5

1 2 5 1 5 1 4 1

1 4 1 2 5 1 6 7

i i iF F a n d F F F

F o r i

n

n

n n n

n n n

n n n

n n n

n n n

n n n

n n n

− −= = = +→ >

=== + + = + + == + + = + + == + + = + + == + + = + + == + + = + + == + + = + + == + + = + + =

Page 53: C Programming by Süleyman Kondakci

kkth Fibonacci Numbersth Fibonacci Numbers

int BinaryFib(k) {

// Input: An integer k

// Output: The kth Fibonacci number

if (k <= 1) then

return k ;

else

return BinaryFib(k-1)+BinaryFib(k-2);

}

Binary recursion

Page 54: C Programming by Süleyman Kondakci

RecursionRecursion

Calculate factorial (n!) of a positive integer:

n! = n(n-1)(n-2)...(n-n-1), 0! = 1! = 1

0! 1, ! (( 1)!) ( 0)n n n n= = − ∀ >⋯

int factorial(int n) {

if (n <= 1)

return 1;

else

return (n * factorial(n -1));

}

Page 55: C Programming by Süleyman Kondakci

Summary of Conditional OperatorsSummary of Conditional Operators

int x=0, y=10, w=20, z, T=1, F=0;

z = (x == 0); /*** logical operator; re sult --> 0 or 1 ***/

z = (x = 0); /*** assignment operator; result --> ***/

z = (x == 1);

z = (x = 15);

z = (x != 2);

z = (x < 10);

z = (x <= 50);

z = ((x=y) < 10); /*** performs assignment, comp ares with 10 ***/

z = (x==5 && y<15);

z = (x==5 && y>5 && w==10);

z = (x==5 || y>5 && w==10);

z = (T && T && F && x && x); /*** ==> F; ***/

z = (F || T || x || x); /*** ==> T; ***/

/*** for && and !!, order is specified, stops when result is known, ***/

/*** value of x doesn't matter ***/

Page 56: C Programming by Süleyman Kondakci

Summary of the Summary of the C C OperationsOperations

• Operators same as in C++ and Java:

• Arithmetic• int i = i+1; i++; i--; i *= 2;

• +, -, *, /, %,

• Relational and Logical• <, >, <=, >=, ==, !=

• &&, ||, &, |, !

• Syntax same as in C++ and Java:• if ( ) { } else { }

• while ( ) { }

• do { } while ( );

• for(i=1; i <= 100; i++) { }

• switch ( ) {case 1: … }

• continue; break;

Page 57: C Programming by Süleyman Kondakci

Arrays & PointersArrays & Pointers

Page 58: C Programming by Süleyman Kondakci

One-Dimensional Arrays

#include <stdio.h>

void main(void){

int number[12]; /* 12 cells, one cell per element */int index, sum = 0;

/* Always initialize arrays before use! */for (index = 0; index < 12; index++) {

// cells are numbered from 0 to 11 not from 1 to 12 !number[index] = index;

}

for (index = 0; index < 12; index = index + 1) {sum += number[index]; /* sum array elements */

}

return;}

Page 59: C Programming by Süleyman Kondakci

Array Initialization

int a[10] = { 1,2,3,4,5,6,7,8,9,10 }; int b[10] = {0}; İnitialize all elements to zeroCharacter arrays that hold strings allow shorthand initializations, like

char str[9] = "I like C";

Or you can use this:

char str[9] = { 'I',' ','l','i','k','e',' ','C','\0 ' };

Page 60: C Programming by Süleyman Kondakci

TwoTwo--dimensional Arraysdimensional Arrays

void fillTable () { int row, col, maxRow, maxCol;int matrix [maxRow][maxCol];

for (int row = 0; row < maxRow; row++) for (int col = 0; col < maxCol; col++)

matrix [row][col] = row + col; }

col1 col2 col3 col4 ...

row1: matrix[0][0] matrix[0][1] matrix[0][2] matrix[0][3] ...

row2: matrix[1][0] matrix[1][1] matrix[1][2] matrix[1][3] ...

row3: matrix[2][0] matrix[2][1] matrix[2][2] matrix[2][3] ...

... ... ... ... ...

rowM: matrix[M][0] matrix[M][1] matrix[M][2] matrix[M][3] ...

Page 61: C Programming by Süleyman Kondakci

TwoTwo--dimensional Arraysdimensional Arrays

void fillTable () {

int row, col, maxRow, maxCol;int matrix [maxRow][maxCol];

for (int row = 0; row < maxRow; row++) for (int col = 0; col < maxCol; col++)

matrix [row][col] = row + col; }

Outer loop executes (with row = 0 ) first, the inner loop fills in the values in the first row of matrix , namely:

matrix [0][0] = row + col ,

matrix [0][1] = row + col ,

matrix [0][2] = row + col ,

and matrix [0][3] = row + col .

The next round of the outer loop fills in the second row of matrix .

The third and final round of the outer loop fills in the final row of matrix .

Page 62: C Programming by Süleyman Kondakci

Printing contents of 2Printing contents of 2--dimensional Arraysdimensional Arrays

void displayTable () {

int row, col;for ( row = 0; row < maxRow; row ++)

{ for (col = 0; col < maxCol; col ++) {

printf("%d\n",matrix [row][col]); }printf("\n");

} }

Page 63: C Programming by Süleyman Kondakci

Initialization of Twoof Two--dimensional Arraysdimensional Arrays

Two-dimensional arrays are initialized in the same way as the one-dimensional arrays, e.g.,

int myArray[6][2] = {

1,1,2,4,3,9,4,16,5,25,6,36

};

Page 64: C Programming by Süleyman Kondakci

More ArraysMore Arrays

•• Array of Array of StringsStringschar name[6];char name[6];

name = {name = { ‘‘ CC’’ ,, ’’ SS’’ ,, ’’ 44’’ ,, ’’ 11’’ ,, ’’ 44’’ ,, ’’ \\ 00’’ }; }; /* /* ’’ \\ 00’’ = end of string */= end of string */

printf("%sprintf("%s ", name); /* print until ", name); /* print until ‘‘ \\ 00’’ */*/

–– Functions to operate on stringsFunctions to operate on strings•• strcpystrcpy , , strncpystrncpy , , strcmpstrcmp , , strncmpstrncmp , , strcatstrcat , ,

strncatstrncat , , etc...etc...

•• #include <strings.h> #include <strings.h> at program startat program start

•• MultiMulti--dimensional arraysdimensional arraysint points[3][4];int points[3][4];points [1][3] = 12; /* NOT points[3,4] */points [1][3] = 12; /* NOT points[3,4] */printf("%dprintf("%d ", points[1][3]);", points[1][3]);

Page 65: C Programming by Süleyman Kondakci

More Array of StringsMore Array of Strings

#include <stdio.h>

int main() {char msg[10]; /* array of 10 chars */char *p; /* pointer to a char */char msg2[]="Hello"; /* msg2 = ‘H’,’e’,’l’,’l’,’o’, ’\0’ */

msg = "Hello"; /* ERROR. msg has a const address.*/p = "Hello"; /* address of "Merhaba" goes into p */

msg = p; /* ERROR. Message has a constant address. * //* cannot change it. */

p = msg; /* OK */

p[0] = ‘H’, p[1] = ‘i’,p[2]=‘\0’; /* *p and msg are now "Hi" */

return 0;}

Page 66: C Programming by Süleyman Kondakci

IterativeIterative sum of array contentssum of array contents

int IterativeArraySum(int A[], int n) {

// Input: An integer array A and an integer n (size)

// Output: The sum of the first n integers

if (n == 1) return A[0];

else

while (n != 0) {

sum = sum + A[n];

n = n – 1;

}

return sum;

}

Page 67: C Programming by Süleyman Kondakci

RecursiveRecursive sum of array contentssum of array contents

int RecursiveArraySum(int A[], int n) {

// Input: An integer array A and an integer n (size)

// Output: The sum of the first n integers

if (n == 1) return A[0];

else

return RecursiveArraySum(A,n-1) + A[n-1];

}

Page 68: C Programming by Süleyman Kondakci

Iterative Reversing of ArrayIterative Reversing of Array

void IterativeReverseArray(int A[], int i,int n) {

// Input: An integer array A and an integers i and n

// Output: The reversal of n integers in A starting at index i

while (n > 1) {

swap (A[i], A[i+n-1]);

i =i +1;

n = n-2;

}

return;

}

Page 69: C Programming by Süleyman Kondakci

Recursive Reversing of ArrayRecursive Reversing of Array

void ReverseArray(int A[], int i, int n) {

// Input: An integer array A and an integers i and n

// Output: The reversal of n integers in A starting at index i

if (n > 1) {

swap (A[i], A[i+n-1]);

ReverseArray(A, i+1, n-2);

}

return;

}

Page 70: C Programming by Süleyman Kondakci

HigherHigher--Order RecursionOrder Recursion

int BinarySum(int A[], int i,int n) {

// Input: An integer array A and an integers i and n

// Output: The sum of n integers in A starting at index i

if (n == 1) {

return A[i];

return BinarySum(A,i,[n/2])+BinarySum(A,i+[n/2],[n/2]);

}

Making recursive calls more than a single call at a time.

Page 71: C Programming by Süleyman Kondakci

Array Operations: SearchingArray Operations: Searching

10 25 11 34 22

i

max=score[i];for (i = 0; i < CLASS_SIZE; ++i) {

if (max <= score[i] ) { max = score[i];

}}

int score [5]

tmp

2

1

Page 72: C Programming by Süleyman Kondakci

Array Operations: SearchingArray Operations: Searching

#include <stdio.h>

#define CLASS_SIZE 10

int main(void){

int i, score[CLASS_SIZE], max;

printf("Input %d How many scores: ", CLASS_SIZE);for (i = 0; i < CLASS_SIZE; ++i) {

scanf("%d", &score[i]);}max=score[i];for (i = 0; i < CLASS_SIZE; ++i) {

if (max <= score[i] ) { max = score[i];

}}

printf("\nMax is: %d\n\n", max);

return 0;}

Page 73: C Programming by Süleyman Kondakci

Array Operations: SortingArray Operations: Sorting

10 25 11 34 22

i jj-1

for (i = 0; i < CLASS_SIZE - 1; ++i)for (j = CLASS_SIZE - 1; j > i; --j)

if (score[j-1] < score[j]) {tmp = score[j-1];

score[j-1] = score[j];score[j] = tmp;

}

int score [5]

tmp

2

1

3

Page 74: C Programming by Süleyman Kondakci

Array Operations: String SortingArray Operations: String Sorting

void string_sort(char *s[]){char tmp; int i, j, length;length=string_length(s);for(i=0; i<length-1; i++) {

for (j=i+1; j<length; j++) {if (strcmp(*s[i], *s[j]) == 0){

tmp=s[i]; s[i]=s[j]; s[j]=tmp;}

}}

}

int string_length(char str[]){int i;for(i=0; i<80; i++){

if(str[i]=='\0') return(i);

}}

Page 75: C Programming by Süleyman Kondakci

Array Operations: SortingArray Operations: Sorting#include <stdio.h>

#define CLASS_SIZE 5

int main(void){

int i, j, score[CLASS_SIZE], sum = 0, tmp;

printf("Input %d scores: ", CLASS_SIZE);for (i = 0; i < CLASS_SIZE; ++i) {

scanf("%d", &score[i]);sum += score[i];

}for (i = 0; i < CLASS_SIZE - 1; ++i) /* bubble sort */

for (j = CLASS_SIZE - 1; j > i; --j)if (score[j-1] < score[j]) { /* check the order */

tmp = score[j-1];score[j-1] = score[j];score[j] = tmp;

}printf("\nOrdered scores:\n\n");for (i = 0; i < CLASS_SIZE; ++i)

printf(" score[%d] =%5d\n", i, score[i]);printf("\n%18d%s\n%18.1f%s\n\n",

sum, " is the sum of all the scores",(double) sum / CLASS_SIZE, " is the class average") ;

return 0;}

Page 76: C Programming by Süleyman Kondakci

Read in WordsRead in Wordsvoid void main(void)main(void) {{

char word[char word[ 3232 ]; ]; // * work space keeps only one word*/* work space keeps only one word*/

char *w[N]; /* an array of pointers to store w ords*/char *w[N]; /* an array of pointers to store w ords*/

int n; /* number of words to be sorted * /int n; /* number of words to be sorted * /

int i;int i;

printf("Enterprintf("Enter wordswords \\ n");n");

for (i = 0; for (i = 0; scanf("%sscanf("%s ", word) == 1 ; ++i) {", word) == 1 ; ++i) {

if (i >= N) break;if (i >= N) break;

if (if ( strlen(word) >= 32strlen(word) >= 32 ) break;) break;

w[i] = (char *)w[i] = (char *) calloc(strlen(wordcalloc(strlen(word ) + 1, ) + 1, sizeof(charsizeof(char ));));

// ** w[i] = new w[i] = new char[strlen(wordchar[strlen(word ) + 1];) + 1]; */*/

if (w[i] == NULL) if (w[i] == NULL) printfprintf ("Empty Word ...("Empty Word ... \\ n");n");

strcpy(w[istrcpy(w[i ], word);], word);

}}

n = i;n = i;

for (i = 0; i < n; ++i) for (i = 0; i < n; ++i) printf("%sprintf("%s \\ nn", w[i]);", w[i]); /* Display words *//* Display words */

}}

Page 77: C Programming by Süleyman Kondakci

Sort WordsSort Wordsvoid sort_words(char *w[], int n) /* void sort_words(char *w[], int n) /* sort sort n n wordswords */*/

{{

int i, j;int i, j;

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

for (j = i + 1; j < n; ++j)for (j = i + 1; j < n; ++j)

if (if ( strcmp(w[istrcmp(w[i ], w[j]) > 0)], w[j]) > 0)

swap(&w[i], &w[j]);swap(&w[i], &w[j]);

}}

void swap(char **p, char **q)void swap(char **p, char **q) {{

char *char * tmptmp ;;

tmptmp = *p;= *p;

*p = *q;*p = *q;

*q = *q = tmptmp ;;

}}

Page 78: C Programming by Süleyman Kondakci

POINTERSPOINTERS

Page 79: C Programming by Süleyman Kondakci

PointerPointers!!!! s!!!! • Pointer= variable containing address of another variable

int x = 5; /* data variable */

int y = 7; /* data variable */

int *ptr = &x; /* & = address operator */

1200

ptr

5

x

x = 5(&x) 1000

y = 7

1000

(&y) 1004

(&ptr) 1200

1200

ptr

10

x

x = 10(&x) 1000

y = 7

ptr = &x = 1000

(&y) 1004

(&ptr) 1200

7

y

7

y

*ptr = 10;

Page 80: C Programming by Süleyman Kondakci

Pointers - 1

float f; /* data variable */

float *f_addr; /* pointer variable */

f_addr = &f; /* & = address operator */

? ?

f f_addr

4300 4304

?

any float

any address

? 4300

f f_addr

4300 4304

Page 81: C Programming by Süleyman Kondakci

Pointers - 2

*f_addr = 3.2; /* indirection operator */

float g=*f_addr; /* indirection:g is now 3.2 */

f = 1.3;

f f_addr

4300 4304

3.2 4300

f f_addr

4300 4304

1.3 4300

Page 82: C Programming by Süleyman Kondakci

Arrays and PointersArrays and Pointers

An array name by itsels is an address or pointer value!An array name by itsels is an address or pointer value!

#define N 100#define N 100

int a[N], i, *p, *q, sum = 0;int a[N], i, *p, *q, sum = 0;

p = a; /* is equivalent to p = &a[0] */; p = a; /* is equivalent to p = &a[0] */;

p = a + 1; /* is equivalent to p = &a[1] */;p = a + 1; /* is equivalent to p = &a[1] */;

int a[i] /* is equivalent to *(a + i) */;int a[i] /* is equivalent to *(a + i) */;

Here *(a + i) is the dereferencing of the expressin a + i that pHere *(a + i) is the dereferencing of the expressin a + i that points i elements positions oints i elements positions past in apast in a

p = a; /* points to the base of array a */p = a; /* points to the base of array a */

q = p + 1; /* equivalent to q =&a[1] */q = p + 1; /* equivalent to q =&a[1] */

printf("%dprintf("%d \\ n", q n", q –– p); p);

printf("%dprintf("%d \\ n", (int) q n", (int) q -- (int) p); (int) p);

for (p = a; p <&a[N]; ++p) sum += *p;for (p = a; p <&a[N]; ++p) sum += *p;

for (i = 0; i < N; ++i) sum += *(a + i);for (i = 0; i < N; ++i) sum += *(a + i);

Page 83: C Programming by Süleyman Kondakci

Pointer ArithmeticPointer Arithmetic

int main(int argc, char* argv[]){double a[2], *p, *q;

p = a; /* points to the base of array a */q = p + 1; /* equivalent to q =&a[1] */printf("=============================\n");printf(" p = %d", p); printf("\n q = %d", q );printf("\n q - p = %d", q - p); printf("\n q - p = %d\n", (int) q - (int) p);printf(" &a[0] = %d", &a[0] ); printf("\n &a[1] = %d &a[1] );

}

Page 84: C Programming by Süleyman Kondakci

#include <stdio.h>

void main(void) {int j;int *ptr;

ptr=&j; /* initialize ptr before using it *//* *ptr=4 does NOT initialize ptr */

*ptr=4; /* j <- 4 assign 4 to j*/

j=*ptr; /* j <- ??? Ask students*/}

Pointer Example

Page 85: C Programming by Süleyman Kondakci

Pointers: SummaryPointers: Summary

int a = 10, b = 2, *p;

p = &a; // p is assigned address of a

b = *p; // b is assigned the value pointed by p

b = *p; is equivalent to b = a;

•An array name is an address or a pointer valueAn array name is an address or a pointer valueAn array name is an address or a pointer valueAn array name is an address or a pointer value

•Arrays and pointers can be subscripted:Arrays and pointers can be subscripted:Arrays and pointers can be subscripted:Arrays and pointers can be subscripted:

int A[10], *p; int i = 0; A[0]=23; p=A;

int b = A[i]; is equivalent to int b = *(A + 0);

int c = p[i]; is equivalent to int c = *(p + i);

p = A; is equivalent to p = &A[0];

p = A + 1; is equivalent to p = &A[1];

Page 86: C Programming by Süleyman Kondakci

Pointers: SummaryPointers: SummaryAll will equally sum the array ellements:All will equally sum the array ellements:All will equally sum the array ellements:All will equally sum the array ellements:

1)1)1)1)

for (p = a; p <&a[N]; ++p)

sum += *p;

2)

for (i = 0; i < N; ++i)

sum += *(a + i);

3)

p = a;

for (i = 0; i < N; ++i)

sum += p[i];

Page 87: C Programming by Süleyman Kondakci

CallCall--byby--valuevalueWhenever variables are passed as arguments to a function, their Whenever variables are passed as arguments to a function, their Whenever variables are passed as arguments to a function, their Whenever variables are passed as arguments to a function, their

values are copied to the function parameters:values are copied to the function parameters:values are copied to the function parameters:values are copied to the function parameters:

int main(){

int a=20; int b=30;

swap (a, b)

printf("%d %d: ", a, b);

return 0;

}

void swap(int x, y) {

int tmp;

tmp=x;

x=y;

y=tmp;

}

Page 88: C Programming by Süleyman Kondakci

Pointers & CallPointers & Call--byby--referencereference

Pointers are passed as arguments to a function, their addresses Pointers are passed as arguments to a function, their addresses Pointers are passed as arguments to a function, their addresses Pointers are passed as arguments to a function, their addresses are are are are

assigned to the function parameters defined as pointers:assigned to the function parameters defined as pointers:assigned to the function parameters defined as pointers:assigned to the function parameters defined as pointers:

int main(){

int a=20; int b=30;

swap (&a, &b)

printf("%d %d: ", a, b);

return 0;

}

void swap(int *x, int *y) {

int tmp;

tmp = *x; // get value pointed by x.

*x = *y; // assign value pointed by y to x

*y = tmp;

}

Page 89: C Programming by Süleyman Kondakci

Why pointer arguments?!

#include <stdio.h>

void swap(int, int);

int main() {int num1 = 5, num2 = 10;swap(num1, num2);printf("num1 = %d and num2 = %d\n", num1, num2);return 0;

}

void swap(int n1, int n2) { /* passed by value */int temp;

temp = n1;n1 = n2;n2 = temp;

}

Page 90: C Programming by Süleyman Kondakci

Why pointer arguments? This is why

#include <stdio.h>

void swap(int *, int *);

int main() {int num1 = 5, num2 = 10;swap(&num1, &num2);printf("num1 = %d and num2 = %d\n", num1, num2);return 0;

}

void swap(int *n1, int *n2) { /* passed and returne d by reference */

int temp;

temp = *n1;*n1 = *n2;*n2 = temp;

}

Page 91: C Programming by Süleyman Kondakci

Arrays as Function Arguments

#include <stdio.h>

void init_array(int array[], int size) ;

void main(void) {int list[5];

init_array(list, 5);for (i = 0; i < 5; i++)

printf("next:%d", array[i]);}

void init_array(int array[], int size) { /* why siz e ? *//* arrays ALWAYS passed by reference */

int i;for (i = 0; i < size; i++)

array[i] = 0; }

Page 92: C Programming by Süleyman Kondakci

int month[12]; /* month is a pointer to base address 430*/

month[3] = 7; /* month address + 3 * int elements=> int at address (430+3*4) is now 7 */

ptr = month + 2; /* ptr points to month[2], => ptr is now (430+2 * int elements)= 438 */

ptr[5] = 12; /* ptr address + 5 int elements

=> int at address (434+5*4) is now 12.Thus, month[7] is now 12 */

ptr++; /* ptr <- 438 + 1 * size of int = 442 */(ptr + 4)[2] = 12; /* accessing ptr[6] i.e., array[9] */

More pointersMore pointers

•• NowNow month[6], *(month+6), (month+4)[2], month[6], *(month+6), (month+4)[2],

ptr[3], *(ptr+3) ptr[3], *(ptr+3) are all the same integer variable.are all the same integer variable.

Page 93: C Programming by Süleyman Kondakci

#include <stdio.h>/* program called with cmd line parameters */

void main(int void main(int argcargc , char *, char * argvargv [])[]) {int ctr;

for (ctr = 0; ctr < argc; ctr = ctr + 1) {printf("Argument #%d is -> |%s|\n", ctr, argv[ctr]);

} /* ex., argv[0] == the name of the program */}

Pointer Example -argc and argv parameters

Page 94: C Programming by Süleyman Kondakci

PointerPointerss to functionto function

•• Advantage ? more flexibilityAdvantage ? more flexibility

int func(); /*function returning integer*/ int *func(); /*function returning pointer to intege r*/ int (*func)(); /*pointer to function returning inte ger*/ int *(*func)(); /*pointer to func returning ptr to in t*/

Page 95: C Programming by Süleyman Kondakci

Pointer to function - Example

#include <stdio.h>

void myproc (int d);void mycaller(void (* f)(int), int param);

void main(void) { myproc(10); /* call myproc with parameter 10*/mycaller(myproc, 10); /* and do the same again ! */

}

void mycaller(void (* f)(int), int param){(*f)(param); /* call function *f with param */

}

void myproc (int d){. . . /* do something with d */

}

Page 96: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 97: C Programming by Süleyman Kondakci

#include <stdio.h>

struct birthday{int month;int day;int year;

};

int main() {struct birthday mybday;mybday.day=1; mybday.month=1; mybday.year=1977;printf("I was born on %d/%d/%d", birth.day,

birth.month, birth.year);return 0;

}

Container Data types: Container Data types: StructuresStructures

Page 98: C Programming by Süleyman Kondakci

Structures Cont’d

struct {char name[41];int age;float height;struct { /* embedded or nested structure */

int month;int day;int year;

} birth;} person ;

struct person me;me.birth.year=1977;………struct person class[60];

/* array of info about everyone in class */

class[0].name="CS206"; class[0].birth.year=1971;……

Page 99: C Programming by Süleyman Kondakci

Accessing Members of StructuresAccessing Members of Structures

struct exp {struct exp {

char c;char c;

int i;int i;

float arr[10];float arr[10];

};};

struct exp exp1; struct exp *expPtr;

exp1.c = exp1.c = ‘‘ AA’’ ; i = 20;; i = 20;

prinf("%c%d ", exp1.c, exp1.i);prinf("%c%d ", exp1.c, exp1.i);

expPtr->c=‘B’; expPtr->i=30;

printf("%c%d ", expPtr->c, expPtr->i);

expPtr = &exp1;

printf("%c%d ", expPtr->c, expPtr->i);

printf("%c%d ", (*expPtr).c, (*expPtr).i);

Page 100: C Programming by Süleyman Kondakci

enum - enumerated data types

#include <stdio.h>enumenum month{month{

JANUARY, /* like #define JANUARY 0 */JANUARY, /* like #define JANUARY 0 */FEBRUARY, /* like #define FEBRUARY 1 */FEBRUARY, /* like #define FEBRUARY 1 */MARCH /* MARCH /* like like #define #define MARCHMARCH22 */*/APRILAPRIL /* /* like like #define #define APRILAPRIL 22 */*/

};};

/* JANUARY is the same as month.JANUARY */

/* alternatively, …. */

enumenum month{month{JANUARYJANUARY == 1, /* like #define JANUARY 1 */1, /* like #define JANUARY 1 */FEBRUARYFEBRUARY= 2= 2 , /* like #define FEBRUARY 2 */, /* like #define FEBRUARY 2 */MARCH MARCH /* /* …… */*/

};};

Page 101: C Programming by Süleyman Kondakci

typedef int numbers;

typdef float kesirli;numbers a_number; /* same as int a_number; */

kesirli fi = 3.14typedef struct person Person;typedef struct person *PrsPtr;// struct person me;Person me; /* same as struct person me; * /PrsPtr you;typedef struct person *Personptr;

Personptr ptrtome; /* same as struct person *ptrto me;*/

typdeftypdef : : Synonym for a data typeSynonym for a data type

•• Easier to rememberEasier to remember

•• For creating cFor creating clean lean and tidy and tidy codecodess

Page 102: C Programming by Süleyman Kondakci

Memory layout of programsMemory layout of programs

Header info

Code

Data - Heap

0

100

400

560

1010

1200

Dynamic memory

Local memory+ function callstack

all normal vars

all malloc()s

Data - stack

Page 103: C Programming by Süleyman Kondakci

#include <stdio.h>

void main(void) {int *int * ptrptr ;;

/* allocate space to hold an int */ptr = malloc(sizeof(int));

/* Put something into the space */** ptrptr =4; =4;

free(ptrfree(ptr ););/* free up the allocated space */

char *w[10]; /* Space for 10 words: pointer array */char word[12]w[i] = calloc(strlen(word) + 1, sizeof(char));/* allocate space to hold a word (string) */ }

Dynamic Memory allocation

•• Explicit allocation and deExplicit allocation and de--allocationallocation

Page 104: C Programming by Süleyman Kondakci

Advanced StructuresAdvanced Structures

Page 105: C Programming by Süleyman Kondakci

#include <stdio.h>

struct birthday{int month;int day;int year;

};

int main() {struct birthday mybday; /* Create structure */mybday.day=1; mybday.month=1; mybday.year=1977;printf("I was born on %d/%d/%d", birth.day,

birth.month, birth.year);return 0;

}

StructuresStructures: Summary: Summary

Page 106: C Programming by Süleyman Kondakci

Array of Structuresstructstruct person{person{

char name[41];char name[41];int age;int age;float height;float height;structstruct { /* embedded structure{ /* embedded structure (( ii çç ii ççe)e) */*/

int month;int month;int day;int day;int year;int year;

} birth;} birth;};};

struct person me;me.birth.year=1977;………

struct person class[2]; /* array of info about everyone in class */

class[0].name="Gül Nihal"; class[0].birth.year=1971;Class[1].name="Mustafa Kemal"; class[0].birth.year=1 883 ; ……

Page 107: C Programming by Süleyman Kondakci

Passing/Returning a structure

/* pass struct to functions by value */void display_year_1(struct birthday void display_year_1(struct birthday mybdaymybday ) {) {

printf("Iprintf("I was born in %was born in % dd\\ nn", ", mybday.yearmybday.year ););}} /* /* -- inefficient: why ? */inefficient: why ? */. . . .

/* pass struct to functions by reference */void display_year_2(struct birthday *void display_year_2(struct birthday * pmybdaypmybday ) {) {

printf("Iprintf("I was born in %was born in % dd\\ nn", ", pmybdaypmybday -- >year);>year);/* warning ! /* warning ! ‘‘ -- >>’’ , not , not ‘‘ .. ’’ , after a , after a structstruct pointer*/ pointer*/

}}. . . ./* return struct by value */

struct birthday get_bday(void){struct birthday newbday;newbday.day=02;newbday;newbday.month=08;newbday.year=1971; return newbday;

}

Page 108: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 109: C Programming by Süleyman Kondakci

File I/O:File I/O:

Writing Data to FilesWriting Data to Files

Reading Data From Files Reading Data From Files

File Input Output OperationsFile Input Output Operations

File I/OFile I/O

Page 110: C Programming by Süleyman Kondakci

File OperationsFile Operations

1)1) Open the fileOpen the file

2)2) Do operations on the FileDo operations on the File

3)3) Close the fileClose the file

Page 111: C Programming by Süleyman Kondakci

Files in C Files in C

•• In C, each file is simply a sequential In C, each file is simply a sequential stream of bytes. C imposes no structure stream of bytes. C imposes no structure on a file.on a file.

•• A file must first be opened properly A file must first be opened properly before it can be accessed for reading or before it can be accessed for reading or writing. When a file is opened, a writing. When a file is opened, a file file handlehandle is associated with the file.is associated with the file.

•• Successfully opening a file returns a Successfully opening a file returns a pointer to (i.e., the address of) a pointer to (i.e., the address of) a file file structurestructure,, which contains a file which contains a file descriptor and a file control block.descriptor and a file control block.

Page 112: C Programming by Süleyman Kondakci

Files in C Files in C

•• The statement: The statement:

FILE *fptr1, *fptr2 ;FILE *fptr1, *fptr2 ;

declares that declares that fptr1fptr1 and and fptr2fptr2 are pointer are pointer variables of type variables of type FILEFILE. They will be . They will be assigned the address of a file descriptor, assigned the address of a file descriptor, that is, an area of memory that will be that is, an area of memory that will be associated with an input or output associated with an input or output stream. stream.

•• Whenever you are to read from or write Whenever you are to read from or write to the file, you must first open the file to the file, you must first open the file and assign the address of its file and assign the address of its file descriptor (or structure) to the file descriptor (or structure) to the file pointer variable. pointer variable.

Page 113: C Programming by Süleyman Kondakci

Opening FilesOpening Files

•• The statement:The statement:

fptr1 = fopen ( "fptr1 = fopen ( "mydatamydata", "r" ) ;", "r" ) ;

would open the file would open the file mydatamydata for input for input (reading). (reading).

•• The statement:The statement:

fptr2 = fopen ("results", "w" ) ;fptr2 = fopen ("results", "w" ) ;

would open the file would open the file resultsresults for output for output (writing). (writing).

•• Once the files are open, they stay open Once the files are open, they stay open until you close them or end the program until you close them or end the program (which will close all files.) (which will close all files.)

Page 114: C Programming by Süleyman Kondakci

Testing for Successful OpenTesting for Successful Open

•• If the file was not able to be opened, If the file was not able to be opened, then the value returned by the then the value returned by the fopen fopen routine is NULL.routine is NULL.

•• For example, let's assume that the file For example, let's assume that the file mydatamydata does not exist. Then:does not exist. Then:

FILE *fptr1 ;FILE *fptr1 ;

fptr1 = fopen ( "fptr1 = fopen ( "mydatamydata", "r") ;", "r") ;

if (fptr1 == NULL) if (fptr1 == NULL)

{{

printfprintf ("File 'mydata' ("File 'mydata' coulcould not open.d not open.\\n") ;n") ;

}}

Page 115: C Programming by Süleyman Kondakci

Parameters for FILE access modeParameters for FILE access mode

Below are modes of opening a file:Below are modes of opening a file:

""ww" " open open writewrite to text fileto text file

""rr" read" read from text filefrom text file

""aa" append to end of file " append to end of file

""wbwb" write binary " write binary

""rbrb" read binary " read binary

""aabb" binary" binary appendingappending

""rr++" " Text file read and writeText file read and write

""ww++" " Text file write and readText file write and read

Page 116: C Programming by Süleyman Kondakci

Reading From FilesReading From Files

•• In the following segment of C language In the following segment of C language

code:code:

int a, b ;int a, b ;

FILE *fptr1, *fptr2 ;FILE *fptr1, *fptr2 ;

fptr1 = fopen ( "fptr1 = fopen ( "mydatamydata", "r" ) ;", "r" ) ;

fscanf ( fptr1, "%fscanf ( fptr1, "%d%dd%d", &a, &b) ;", &a, &b) ;

the the fscanffscanf function would read values function would read values

from the file "pointed" to by from the file "pointed" to by fptr1fptr1 and and

assign those values to assign those values to aa and and bb..

Page 117: C Programming by Süleyman Kondakci

End of FileEnd of File

•• The endThe end--ofof--file indicator informs the file indicator informs the program when there are no more data (no program when there are no more data (no more bytes) to be processed.more bytes) to be processed.

•• There are a number of ways to test for the There are a number of ways to test for the endend--ofof--file condition. One is to use the file condition. One is to use the feoffeoffunction which returns a function which returns a truetrue or or falsefalsecondition:condition:

fscanf (fptr1, "%d", &var) ;fscanf (fptr1, "%d", &var) ;

if ( feof (fptr1) )if ( feof (fptr1) )

{{

printf ("Endprintf ("End--ofof--file encountered.file encountered.\\n) ;n) ;

}}

Page 118: C Programming by Süleyman Kondakci

End of FileEnd of File

•• There are a number of ways to test for There are a number of ways to test for

the endthe end--ofof--file condition. Another way is file condition. Another way is

to use the value returned by the to use the value returned by the fscanffscanf

function:function:

int istatus ;int istatus ;

istatus = fscanf (fptr1, "%d", &var) ;istatus = fscanf (fptr1, "%d", &var) ;

if ( istatus == EOF )if ( istatus == EOF )

{{

printfprintf ("End("End--ofof--file encountered.file encountered.\\n) ;n) ;

}}

Page 119: C Programming by Süleyman Kondakci

Writing To FilesWriting To Files

•• Likewise in a similar way, in the Likewise in a similar way, in the

following segment of C language code:following segment of C language code:

int a = 5, b = 20;int a = 5, b = 20;

FILE *fptr2 ;FILE *fptr2 ;

fptr2 = fopen ( "results", "w" ) ;fptr2 = fopen ( "results", "w" ) ;

fprintf ( fptr2, "%d %fprintf ( fptr2, "%d %dd\\nn", a, b ) ;", a, b ) ;

the the fprintf fprintf functions would write the functions would write the

values stored in values stored in aa and and bb to the file to the file

"pointed" to by "pointed" to by fptr2fptr2. .

Page 120: C Programming by Süleyman Kondakci

Closing FilesClosing Files

•• The statements:The statements:

fclose ( fptr1 ) ;fclose ( fptr1 ) ;

fclose ( fptr2 ) ;fclose ( fptr2 ) ;

will close the files and release the will close the files and release the

file descriptor space and I/O buffer file descriptor space and I/O buffer

memory. memory.

Page 121: C Programming by Süleyman Kondakci

Reading and Writing FilesReading and Writing Files

#include <stdio.h>#include <stdio.h>

void main ( )void main ( )

{{

FILE *outfile, *infile ;FILE *outfile, *infile ;

int b = 5, f ;int b = 5, f ;

float a = 13.72, c = 6.68, e, g ;float a = 13.72, c = 6.68, e, g ;

outfile = fopen ("outfile = fopen (" testdatatestdata ", "w") ;", "w") ;

fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ;fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ;

fclose (outfile) ;fclose (outfile) ;

infileinfile = = fopenfopen ("(" testdatatestdata ", "r") ;", "r") ;

fscanffscanf (( infile,"%finfile,"%f %d %f", &e, &f, &g) ;%d %f", &e, &f, &g) ;

printfprintf ("%6.2f%2d%5.2f("%6.2f%2d%5.2f \\ n", a, b, c) ;n", a, b, c) ;

printfprintf ("%6.2f,%2d,%5.2f("%6.2f,%2d,%5.2f \\ n", e, f, g) ;n", e, f, g) ;

}}

1234567890123456789012345678901234567890

********************************************************13.72 5 6.6813.72 5 6.68

13.72, 5, 6.6813.72, 5, 6.68

Page 122: C Programming by Süleyman Kondakci

More Lines in a File?More Lines in a File?

•• The last aThe last assignmentssignment requires us to read requires us to read several lines of some information from a file several lines of some information from a file and write it out to the screen and to a file. and write it out to the screen and to a file. (Sounds repetitive, doesn't it?)(Sounds repetitive, doesn't it?)

•• Simple repetitive tasks are easily performed Simple repetitive tasks are easily performed with a "with a "forfor" " or "or "whilewhile" " loop. loop. For example:For example:

int int ii, , iiii = = 00;;

FILE *fptr2 ;FILE *fptr2 ;

fptr2 = fptr2 = fopenfopen ( "results", "w" ) ;( "results", "w" ) ;

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

{{

fprintffprintf ( fptr2, "%d %( fptr2, "%d %dd\\nn", a, b ) ;", a, b ) ;

}}

fclosefclose ((fptr);fptr);

Page 123: C Programming by Süleyman Kondakci

Exp: Change the case of letters in a file

#include <stdio.h>

#include <stdlib.h>

#define BUFSIZE 1024

int main(int argc, char *argv[]) {

char mybuf[BUFSIZE], *p;

int in_fd, out_fd, n;

in_fd = open(argv[1], "r");

out_fd = open(argv[2], "w");

while ((n = read(in_fd, mybuf, BUFSIZE)) > 0) {

for (p = mybuf; p - mybuf < n; ++p)

if (islower(*p)) *p = toupper(*p);

else if (isupper(*p)) *p = tolower(*p);

write(out_fd, mybuf, n);

}

close(in_fd); close(out_fd);

return 0;

}

Page 124: C Programming by Süleyman Kondakci

Change the case of letter in a file

The previous code (conv.c) will convert the content of a file having lowercase letters to corresponding capital (uppercase) letter s

Do the followings on UNIX/linux:

gcc –o toupper conv.c

./toupper infile.txt outfile.txt

Page 125: C Programming by Süleyman Kondakci

Replicate a file with caps

#include <ctype.h>

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char *argv[]) {

int c; FILE *fp, *tmp_fp;

if (argc != 2) {

printf("\n%s%s%s\n\n%s\n\n", "Usage: "

argv[0], " filename");

exit(1);

}

if (fp=fopen(argv[1],"rw") == NULL) {

printf("Cannot open %s - bye!\n", argv[1]);

exit(1);

}

fp = fopen(argv[1], "r+");

tmp_fp = tmpfile();

while ((c = getc(fp)) != EOF)

putc(toupper(c), tmp_fp);

rewind(tmp_fp);

fprintf(fp, "---\n");

while ((c = getc(tmp_fp)) != EOF)

putc(c, fp);

return 0;

}

Page 126: C Programming by Süleyman Kondakci

Double Space a FileDouble Space a File

#include <stdio.h> #include <stdlib.h>

void double_space(FILE *, FILE *);

void prn_info(char *);

int main(int argc, char **argv) {

FILE *ifp, *ofp;

if (argc != 3) {

prn_info(argv[0]);

exit(1);

}

ifp = fopen(argv[1], "r"); /* open for reading */

ofp = fopen(argv[2], "w"); /* open for writing */

double_space(ifp, ofp);

fclose(ifp);

fclose(ofp);

return 0;

}

Page 127: C Programming by Süleyman Kondakci

Double Space a File (contDouble Space a File (cont’’ d)d)

void double_space(FILE *ifp, FILE *ofp) {

int c;

while ((c = getc(ifp)) != EOF) {

putc(c, ofp);

if (c == '\n')

putc('\n', ofp); /* found a newline - duplicate it */

}

}

void prn_info(char *pgm_name){

printf("\n%s%s%s\n\n%s%s\n\n",

"Usage: ", pgm_name, " infile outfile",

"The contents of infile will be double-spaced ",

"and written to outfile.");

}

Page 128: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 129: C Programming by Süleyman Kondakci

The C PreprocessorThe C Preprocessor

•• Preprocessors extend power of CPreprocessors extend power of C

•• Lines starting with Lines starting with ## are preprocessing are preprocessing

directives.directives.

•• #define#define macro facility generates inline macro facility generates inline

code in place of functions. They provide code in place of functions. They provide

fatser execution. Examples:fatser execution. Examples:

•• #include <stdio.h>#include <stdio.h>

•• #include "filename"#include "filename"

•• #define identifier token_string#define identifier token_string•• #define (identifier,#define (identifier, ……, identifier) token_string, identifier) token_string

Page 130: C Programming by Süleyman Kondakci

The Use of The Use of #define#define

•• #define PI 3.14159#define PI 3.14159•• #define size 1000#define size 1000•• #define seconds_per_day (60*60*2)#define seconds_per_day (60*60*2)•• #define EQ ==#define EQ ==•• #define LT <#define LT <•• #define LTE <=#define LTE <=•• #define NOT !=#define NOT !=•• Example:Example:

int main(){int main(){int i=0int i=0

while (i NOT 5){while (i NOT 5){printf ("hello!");printf ("hello!");i++;i++;

}}return 0;return 0;

}}

Page 131: C Programming by Süleyman Kondakci

MacrosMacros•• Macros are small codes that can be used Macros are small codes that can be used

instead of functions.instead of functions.

•• They execute very fast!They execute very fast!

•• Syntax: Syntax:

#define (identifier,#define (identifier, ……, identifier) token_string, identifier) token_string#define sq(x) ((x) * (x))#define sq(x) ((x) * (x))#define min(x,y) (((x) < (y)) ? (x) : (y))#define min(x,y) (((x) < (y)) ? (x) : (y))

How to callHow to call these macrosthese macros ??int u,v,m,w = 6;int u,v,m,w = 6;sq(7 + w) expands to ((7 + 6) * (7 + 6))sq(7 + w) expands to ((7 + 6) * (7 + 6))sq(sq(5)) expands to what?sq(sq(5)) expands to what?scanf("%d%d", &u,&v);scanf("%d%d", &u,&v);m = min(u,v);m = min(u,v);

Page 132: C Programming by Süleyman Kondakci

Macros With ArgumentsMacros With Arguments

#include <stdio.h>#include <stdio.h>

#include <stdlib.h>#include <stdlib.h>

#include <time.h>#include <time.h>

#define random_char() (rand() % 26 + 'a')#define random_char() (rand() % 26 + 'a')

#define random_int(x) (rand() % x)#define random_int(x) (rand() % x)

#define max(x,y) (((x) > (y)) ? (x) : (y))#define max(x,y) (((x) > (y)) ? (x) : (y))

#define min(x,y) (((x) < (y)) ? (x) : (y))#define min(x,y) (((x) < (y)) ? (x) : (y))

int main() {int main() {

char a; int r; char a; int r;

srand(time(NULL));srand(time(NULL));

a = random_char();a = random_char();

r = random_int(100);r = random_int(100);

printf("Random char = %cprintf("Random char = %c \\ t Random int = %d t Random int = %d \\ n",a,r);n",a,r);

printf("Min (%d and %d) = %d printf("Min (%d and %d) = %d \\ n",r, a, min(r,a));n",r, a, min(r,a));

printf("Max (%d and %d) = %d printf("Max (%d and %d) = %d \\ n", r, a, max(r,a));n", r, a, max(r,a));

return 0;return 0;

}}

Page 133: C Programming by Süleyman Kondakci

Some Macros in stdio.h and ctype.hSome Macros in stdio.h and ctype.h

•• In the file In the file ctype.hctype.h we havewe have

•• #define getchar() getc(stdin)#define getchar() getc(stdin)

•• #define putcahr() putc((c),stdout)#define putcahr() putc((c),stdout)

Your code should contain this at the topYour code should contain this at the top

#include <ctype.h>#include <ctype.h>

Page 134: C Programming by Süleyman Kondakci

More Usefull MacrosMore Usefull Macros

c is an codec is an codeisascii(c) isascii(c)

c is printable but not a spacec is printable but not a spaceisgraph(c) isgraph(c)

c is a printable characterc is a printable characterisprint(c) isprint(c)

c is a punctation characterc is a punctation characterispunct(c) ispunct(c)

c is a white space characterc is a white space characterisspace(c) isspace(c)

c is a hexadecimal digitc is a hexadecimal digitisxdigit(c) isxdigit(c)

c is a letter or digitc is a letter or digitisalnum(c) isalnum(c)

c is a digitc is a digitisdigit(c) isdigit(c)

c is lowercase letterc is lowercase letterislower(c) islower(c)

c is an uppercase letterc is an uppercase letterisupper(c) isupper(c)

c is letterc is letterisalpha(c) isalpha(c)

Nonzero (true) returned ifNonzero (true) returned ifMacroMacro

Page 135: C Programming by Süleyman Kondakci

ConversionConversion

ASCII valueASCII valuetoascii(c)toascii(c)

Lowercase value of cLowercase value of ctolower(c)tolower(c)

Uppercase value of cUppercase value of ctoupper(c) toupper(c)

Value returnedValue returnedCall to functionCall to function

Page 136: C Programming by Süleyman Kondakci

Intro to Algorithms & Data StructuresIntro to Algorithms & Data Structures

Page 137: C Programming by Süleyman Kondakci

User Defined Data TypesUser Defined Data Types

•• All related data are collected in All related data are collected in

conglomerate structuresconglomerate structures

•• Many types of conglomerate structures:Many types of conglomerate structures:

–– StacksStacks

–– Queues (FIFO = First in First Out)Queues (FIFO = First in First Out)

–– TreesTrees

–– VectorsVectors

–– Linked ListsLinked Lists

•• Single Single

•• DoubleDouble

•• CircleCircle

Page 138: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 139: C Programming by Süleyman Kondakci

What Are Stacks ?What Are Stacks ?

PUSHPUSH POPPOP

00

MAXMAX

Underflow

Overflow

--11

Page 140: C Programming by Süleyman Kondakci

const int MaxStack = 1024;

const char EmptyFlag = '\0';

char items [ MaxStack ];

int top;

enum { FullStack = MaxStack, EmptyStack = -1 };

/* Required tack functions are: */

push(char);

char pop();

bool empty(); bool full();

StacksStacks

Page 141: C Programming by Süleyman Kondakci

Stack: ExampleStack: Example

const int MaxStack = 1024; const char EmptyFlag = '\0';

char items [ MaxStack ];

int top;

enum { FullStack = MaxStack, EmptyStack = -1 };

void push(char); char pop();

bool empty(); bool full();

void push(char c){

if (full()) return;

items[++top] = c;

}

char pop(){

if (empty()) return EmptyFlag;

return items[top--];

}

Page 142: C Programming by Süleyman Kondakci

Stacks: ExampleStacks: Examplebool full() {

if (top + 1 == FullStack) {

cerr << "Stack Full at " << MaxStack << endl;

return true;

}

return false;

}

bool empty(){

if (top == EmptyStack) {

cerr <<"Stack empty" <<endl;

return true;

}

return false;

}

void main(void){

push(‘A’); push(‘B’);

pop();pop();

pop();

}

Page 143: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 144: C Programming by Süleyman Kondakci

Linked ListsLinked Lists

•• Nodes: Represent data storage Nodes: Represent data storage

pointspoints

•• Pointers: are used to handle nodes Pointers: are used to handle nodes

int a char cchar *name = "kerem"

Head next Tail next

NULL

A node

Page 145: C Programming by Süleyman Kondakci

Linked List OperationsLinked List Operations

•• Creating a list element,Creating a list element,

•• PrependingPrepending elements on top of lists,elements on top of lists,

•• Inserting elements into lists,Inserting elements into lists,

•• Appending to end of lists, Appending to end of lists,

•• Finding/searching elements in the Finding/searching elements in the

listlist

•• Sorting elements,Sorting elements,

•• Deleting,Deleting,

•• Moving elements Moving elements aroundaround in the listin the list..

Page 146: C Programming by Süleyman Kondakci

Linked List TypesLinked List Types

Single linked listsSingle linked lists

NULL

Headnext

Tail next

A node

previous previous

next

int a char cchar *name = "kerem"

Head nextTail next

NULL

A node

next

Double linked lists

Circle linked listsint a char cchar *name = "kerem"

Head next Tail next

A node

Page 147: C Programming by Süleyman Kondakci

Linked ListsLinked Lists

struct list {

int data;

struct list *next;

}a;

NULL

data next

struct list a, b,c

a.data = 1; b.data=1;c.data=3;

a.next=b.next=c.next = NULL;

1 next 2 next 3 next

1 next 2 next 3 next

a.next = &b;

b.next =&c;NULL

Page 148: C Programming by Süleyman Kondakci

Linear Linked ListsLinear Linked Lists

#include <assert.h> #include <stdio.h>

#include <stdlib.h>

#define MAXLINE 100

typedef char DATA; /* will use char in examples */

struct linked_list {

DATA d;

struct linked_list *next;

};

typedef struct linked_list ELEMENT;

typedef ELEMENT *LINK;

Page 149: C Programming by Süleyman Kondakci

Linear Linked ListsLinear Linked Lists

LINK head;

head = malloc(sizeof(ELEMENT));

head->d =‘A’;

head->next = NULL;

/* Let’s add a second element */

head ->next = malloc(sizeof(ELEMENT));

head->next->d =‘B’;

head->next ->next = NULL;

A next

NULL

A next B next

NULL

/* Let’s add a 3rd element */

head ->next->next = malloc(sizeof(ELEMENT));

head->next->d ->next =‘C’;

head->next ->next ->next = NULL;

B next C next

NULL

A next

Page 150: C Programming by Süleyman Kondakci

Creating a List: 1st Declare the ListCreating a List: 1st Declare the List

#include <assert.h>

#include <stdio.h>

#include <stdlib.h>

#define MAXLINE 100

typedef char DATA; /* will use char in examples */

struct linked_list {

DATA d;

struct linked_list *next;

};

typedef struct linked_list ELEMENT;

typedef ELEMENT *LINK;

Page 151: C Programming by Süleyman Kondakci

Creating a List: Using IterationCreating a List: Using Iteration

#include "list.h"

LINK s_to_l(char s[]) {

LINK head = NULL, tail; int i;

if (s[0] != '\0') { /* first element */

head = malloc(sizeof(ELEMENT));

head -> d = s[0];

tail = head;

for (i = 1; s[i] != '\0'; ++i) { /* add to tail */

tail -> next = malloc(sizeof(ELEMENT));

tail = tail -> next;

tail -> d = s[i];

}

tail -> next = NULL; /* end of list */

}

return head;

}

Page 152: C Programming by Süleyman Kondakci

Creating a List: Using RecursionCreating a List: Using Recursion

#include "list.h"

LINK string_to_list(char s[]) {

LINK head;

if (s[0] == '\0') /* base case */

return NULL;

else {

head = malloc(sizeof(ELEMENT));

head -> d = s[0];

head -> next = string_to_list(s + 1);

return head;

}

}

Page 153: C Programming by Süleyman Kondakci

Count Elements of a List: Using IterationCount Elements of a List: Using Iteration

#include "list.h"

int count_list(LINK head)

{

int count;

for (; head != NULL; head = head -> next)

++count;

return count;

}

Page 154: C Programming by Süleyman Kondakci

Count Elements of a List: Using RecursionCount Elements of a List: Using Recursion

#include "list.h"

int count_list(LINK head)

{

if (head == NULL) return 0;

else

return(1 + count_list(head -> next));

}

Page 155: C Programming by Süleyman Kondakci

Print Elements in a List: Using IterationPrint Elements in a List: Using Iteration

#include "list.h"

void wrt_list(LINK head)

{

LIST p;

if (head == NULL) printf("NULL list");

else

for (p = head; p != NULL; p = p -> next)

putchar(p -> d);

}

Page 156: C Programming by Süleyman Kondakci

Print Elements in a List: Using RecursionPrint Elements in a List: Using Recursion

#include "list.h"

void wrt_list(LINK head)

{

if (head == NULL) printf("NULL list");

Else {

printf("%c àààà ", head -> d);

wrt_list(head ->next);

}

}

Page 157: C Programming by Süleyman Kondakci

Insertion of Elements in a ListInsertion of Elements in a List

#include "list.h"

Void insert(LINK p1, LINK p2, LINK q)

{

Assert (p1-> next == p2);

p1->next = q;

q->next = p2;

}

B next

C next

NULL

A next

q

p1

p2

initially

Page 158: C Programming by Süleyman Kondakci

Delete Elements in a List: Using IterationDelete Elements in a List: Using Iteration

#include "list.h"

void delete(LINK head)

{

LIST p;

if (head == NULL) printf("NULL list");

else

for (p = head; p != NULL; p = p -> next)

free(p);

}

Page 159: C Programming by Süleyman Kondakci

Delete Elements in a List: RecursivelyDelete Elements in a List: Recursively

#include "list.h"

void elete_list(LINK head)

{

if (head != NULL) {

delete_list(head ->next);

free(head);

}

}

Page 160: C Programming by Süleyman Kondakci

C ProgrammingC Programming

Page 161: C Programming by Süleyman Kondakci

A linked list implementation of a queueA linked list implementation of a queue

data next

daat next

NULL

data next

cntfrontrear

queue

elemelem

elem

Queue: First-In-First-Out (FIFO) data structure

Page 162: C Programming by Süleyman Kondakci

The header file: queue.hThe header file: queue.h

#define EMPTY 0

#define FULL 10000

typedef unsigned int data;

typedef enum {false, true} boolean;

struct elem { /* an element in the queue */

data d;

struct elem *next;

};

typedef struct elem elem;

struct queue {

int cnt; /* a count of the elements */

elem *front; /* ptr to the front element */

elem *rear; /* ptr to the rear element */

};

typedef struct queue queue;

Page 163: C Programming by Süleyman Kondakci

The header file: queue.hThe header file: queue.h (cont(cont’’ d)d)

void initialize(queue *q);

void enqueue(data d, queue *q);

data dequeue(queue *q);

data front(const queue *q);

boolean empty(const queue *q);

boolean full(const queue *q);

Page 164: C Programming by Süleyman Kondakci

Basic queue routines (contBasic queue routines (cont’’ d)d)

#include "queue.h"

void initialize(queue *q){

q -> cnt = 0;

q -> front = NULL;

q -> rear = NULL;

}

data dequeue(queue *q){

data d;

elem *p;

d = q -> front -> d;

p = q -> front;

q -> front = q -> front -> next;

q -> cnt--;

free(p);

return d;

}

Page 165: C Programming by Süleyman Kondakci

Basic queue routinesBasic queue routines (cont(cont’’ d)d)

void enqueue(data d, queue *q){

elem *p;

p = malloc(sizeof(elem));

p -> d = d;

p -> next = NULL;

if (!empty(q)) {

q -> rear -> next = p;

q -> rear = p;

} else

q -> front = q -> rear = p;

q -> cnt++;

}

Page 166: C Programming by Süleyman Kondakci

Basic queue routinesBasic queue routines (cont(cont’’ d)d)

data front(const queue *q){

return (q -> front -> d);

}

boolean empty(const queue *q){

return ((boolean) (q -> cnt == EMPTY));

}

boolean full(const queue *q){

return ((boolean) (q -> cnt == FULL));

}

Page 167: C Programming by Süleyman Kondakci

C ProgrammingC Programming


Recommended