C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

53
C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems

Transcript of C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Page 1: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

C Programming Day 3based upon Practical C Programming by Steve

Oualline

CS550Operating Systems

Page 2: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Constants

• Can be defined as macros or as true constants

#include <stdio.h>

#define PI 3.14 //A macro

int main(...){ declarations statements}

Page 3: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Constants

• or you can use the following:

const double PI = 3.14;

• It is appropriate to use const instead of #define for constants.

• macros simply substitute the text of the macro where ever the text is placed within the code.

Page 4: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Multi-dimensional Arrays

type name [dim1][dim2]...

int main(int argc, char ** argv){ int arr[2][3] = { {1, 2, 3}, {4, 5, 6} }

printf("%d %d %d\n", arr[0][0], arr[0][1], arr[0][2]); printf("%d %d %d\n", arr[1][0], arr[1][1], arr[1][2]);

return 0;}

Page 5: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Multi-dimensional Arrays

• Result:

1 2 34 5 6

Page 6: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Relational operators

• >= greater than or equal to• <= less than or equal to• > greater than• < less than

Page 7: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Relational Expressions

• Relational expressions in C give a true or false value but not in the same way as java

• In C, 0 or zero is false (an integer), and anything else is true (positive or negative integers)

• The compiler should give a value of 1 upon evaluation of a true expression and 0 upon evaluation of a false expression

Page 8: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example

(9 > 6) + 5

--> 1 + 5--> 6

c = (a > b) + 2;

• Result is 3 if a > b• Result is 2 if a <= b

Page 9: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Assignment vs. Equality

• In C, you can use assignment statements as an expression for an if statement.

//The following is true unless 0 is//assigned to aif(a = b) do something

• a == b checks equality

Page 10: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Evaluating Boolean Expressions

• Remember, 0 is false and all other values whether positive or negative are

• true.

• == --> equal to• 1 == 1 --> true --> 1• 7 == 5 --> false --> 0

• != --> not equal to• 7 != 7 --> false --> 0• 25 != -3 --> true --> 1

Page 11: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Evaluating Boolean Expressions

! --> negation

!1 --> 0!0 --> 1!-3943 --> 0

!(22 == 22) --> !1 --> 0

Page 12: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

And/Or

&& --> and|| --> or

expr1 && expr2expr1 || expr2

• && and || are short circuit operators in C• We stop after evaluating the first expression if we

know the result.

Page 13: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

If Statementsif(expr) statement;

• statement is evaluated if expr is true.

if(expr){ //Compound statement stmt1; ... stmt_n;}

• Compound statement is evaluated if expr is true

Page 14: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

If-Else Statementsif(expr) stmt1;else stmt2;

if(expr){ multiple stmts;}else{ multiple stmts;}

Page 15: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Nested If Statementsa = 1;b = 2;

if(a == 1) if(b == 2) printf("***\n");

if(a == 1){ if(b == 3) printf("b is 3\n"); else printf("b is not 3\n");}

Page 16: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example Program#include <stdio.h>

int main(int argc, char ** argv){ int x, y, z, min;

printf("Enter 3 ints: "); scanf("%d %d %d", &x, &y, &z);

if(x < y) min = x; else min = y;

if(min > z) min = z;

printf("%d is the minimum.\n", min); return 0;}

Page 17: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example Program

#include <stdio.h>const int DEBUG = 1;

int main(int argc, char ** argv){ ... if(DEBUG) printf("DEBUG: %s\n", debug_str); return 0;}

Page 18: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

While Loops

while ( expr) stmt;

while (expr){ multiple stmts;}

Page 19: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

While Loop Example

int i = 0; sum = 0;

while (i <= 10){ sum += i; i++;}

• Tracesum is 55i is 11

Page 20: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Sentinel Loopswhile(!sentinel){

do something}

• Example:

read input

while(strcmp(input, "-999") != 0){ do something read input again}

Page 21: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example Sentinel Loop

char sentinel[] = "SENTINEL";char line[100];

int a;

fgets(line, sizeof(line), stdin);

//move the null character to cover//the newline characterline[strlen(line) - 1] = '\0';

Page 22: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example Sentinel Loopwhile(strcmp(line, sent) != 0){ sscanf(line, "%d", &a);;

if(a % 2 == 0) printf("a is even\n"); else printf("a is odd\n");

fgets(line, sizeof(line), sdtin);

line[strlen(line) - 1] = '\0';}

Page 23: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Issues with Loops

• Programs with loops may run forever

• Ctrl-C in linux/unix "kills" or ends a program

• If Ctrl-C won't work, open another window and use the following command

• ps -fu username

Page 24: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Issues with Loops• Find the PID of the program (e.g. 800) then run the following

command:

kill PID

• where PID is the process id number (e.g. 800)

• If that doesn't work, use a "hard kill"

kill -9 PID

• where PID is the process id number (e.g. 800)

Page 25: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

If-elseif-else statementsif(condition1) stmt1;else if(condition2) stmt2;else if(condition3){ stmt3a; stmt3b;}else if(cond4) stmt4;...else //not required but often necessary stmt_n;

Page 26: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Grades Exampleint pct_grade;

scanf("%d", &pct_grade);if(pct_grade <= 100 && pct_grade >= 90) printf("A\n");else if(pct_grade < 90 && pct_grade >= 80) printf("B\n");else if(pct_grade < 80 && pct_grade >= 70) printf("C\n");else if(pct_grade < 70 && pct_grade >= 60) printf("D\n");else if(pct_grade < 60 && pct_grade >= 0) printf("F\n");else printf("Error: %d is an invalid grade\n", pct_grade);

Page 27: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

For Loops

• In java the following works:

//The "int i" will cause an error//in ANSI Cfor(int i = 0; i < n; i++) stmt;

• Do NOT declare a variable in your C for loop header unless you are using C99

Page 28: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

For Loops• This is correct:

int i;...for(i = 0; i < n; i++) //do work

for( initialization; conditional expr; expr) //do work

//acts just like a while loopfor( ; cond. expr; ) stmt;

Page 29: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

More for loop examplesfor( ; i < n; ) i++;

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

while( i < n) i++;

int i, sum = 0;

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

Page 30: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Loop tools

• break; //Takes you to the end of a loop

• continue; //Take you to the beginning of a loop

Page 31: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

While loop examplewhile(true){ while(i < n) { if(i == 7) break; else if(i == 2) { i += 2; continue; } i++; } stmt; break;}

Page 32: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

More loop examples

for(i = 0, j = n; j > i; i++, j--) //use 2 math expressions

//Find out if a string is a//palindromefor(i = 0, j = n; i < j; i++, j--) if(str1[i] != str1[j]) printf(”%s%s”,“This string is”, “ not a palindrome\n");

Page 33: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example Program#include <stdio.h>

int main(int argc, char ** argv){ int total, current, counter; total = 0;

for(counter = 0; counter < 5; counter++) { printf("Enter a number: "); scanf("%d", &current); total += current; }

printf("%d is the total\n", total);

return 0;}

Page 34: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

• Input:

12345

• Output:

15 is the total

Page 35: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Another examplechar line[100];int result, value;char operator;result = 0;

while(1){ printf("Result: %d\n", result); printf("Enter an operator and a number: "); fgets(line, sizeof(line), stdin);

sscanf(line, "%c %d", &operator, &value);

Page 36: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Another Example Continued

if(operator == 'q' || operator == 'Q') break; else if(operator == '+') result += value; else if(operator == '-') result -= value; else if(operator == '*') result *= value;

Page 37: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Another Example Continued

else if(operator == '/') { if(value == 0) printf("Error: divide by zero.\n"); else result /= value; } else printf("%c is not a valid operator.\n", operator);} //End whilereturn 0;

Page 38: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Switch example#include <stdlib.h>

...

switch(operator){case 'q':case 'Q': exit(0); break;case '+': result += value; break;case '-': result -= value; break;case '*': result *= value; break;case '/': if(value == 0) printf("Error: cannot divide by zero.\n"); else result /= value; break;default: continue;}

Page 39: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Functions

• All C programs are made up of one or more functions.• main is a function.• Functions are like methods in java, but have no

associated objects.• When a program encounters a function, it is called or

invoked.• We have seen many functions already:• printf, scanf, fgets, sscanf, strlen, sqrt, sin, cos, exit, etc.

Page 40: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example#include <stdio.h>

//Function prototype - like a declaration//for a function.void print_message(void);

//Function header for mainint main(int argc, char ** argv){ print_message(); return 0;}

//Function definition for print_messagevoid print_message(void){ //Function header //Function body printf("Message from print_message\n");}

Page 41: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Functions

• function header consists of a return type, function name and

• parameters.

• Recall that we use top-down design to break programs into pieces

• so they are easier to think about

• In general, functions & programs are set up as follows on the next slide

Page 42: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Functions//Provide prototypes firstreturn_type fn_name(parameter type list); //you must provide types

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

//Provide function definitions last//you must provide names and typesreturn_type fn_name(parameter list){ //function body (statements) goes here ...}

Page 43: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Formal Parameters

• Parameters in the function header• Place holders for values passed into the function

when the function is called• They exist only in the function body

//a and b are the formal parametersint min (int a, int b) { ...}

Page 44: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Actual parameters

• Values/parameters passed into the function when it is called.

int main (int argc, char ** argv){ int c, d; ... minimum = min(c, d); //c & d are actual parameters}

Page 45: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example

int min(int a, int b){ if(a < b) return a; return b;}

Page 46: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Example Continued

int main(int argc, char ** argv){ int c, d; int minimum; c = 5; d = 7;

minimum = min(c, d);

//Print the minimum here}

Page 47: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Return Statements

• You can have as many return statements as you want in your functions

return (expr);

• If you have a void function (i.e. it returns nothing) use the following:

return;

Page 48: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Pseudorandom Numbers• use #include <stdlib.h> to get the pseudorandom number

generator to use the pseudorandom number generator, call rand()

• This returns an int value between 0 and RAND_MAX

• Remember that rand() is a very poor pseudorandom number generator

• You should use a generator such as the Mersenne Twister instead

• (rand() % 6) + 1 will provide a random number between 1 and 6, inclusive.

Page 49: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Seeding The Generator• To seed the random number generator use the following function

srand(seed);

• where seed is an unsigned integer variable.

#include <time.h>

• to get the clock value use time(0)

• To seed with the clock use:

srand(time(0));

Page 50: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Assertions

• To use assertions

#include <assert.h>

assert(expr);

• Ex. assert(a > 0);

Page 51: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Header File• When developing larger programs, .h files are used to contain

constants,• global variables, and function prototypes.

#ifndef PROGRAM_H#define PROGRAM_H

//Put prototypes here int min(int, int);int max(int, int);

#endif

Page 52: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Library File

• In your .c file

#include "program.h"

int min(int a, int b){ ...}

Page 53: C Programming Day 3 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.

Main Function

• In main.c

#include "program.h”#include <stdio.h>

int main(...){ ... minval = min(a,b);}