View
218
Download
0
Category
Preview:
Citation preview
C Programming Day 3based upon Practical C Programming by Steve
Oualline
CS550Operating Systems
Constants
• Can be defined as macros or as true constants
#include <stdio.h>
#define PI 3.14 //A macro
int main(...){ declarations statements}
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.
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;}
Multi-dimensional Arrays
• Result:
1 2 34 5 6
Relational operators
• >= greater than or equal to• <= less than or equal to• > greater than• < less than
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
Example
(9 > 6) + 5
--> 1 + 5--> 6
c = (a > b) + 2;
• Result is 3 if a > b• Result is 2 if a <= b
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
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
Evaluating Boolean Expressions
! --> negation
!1 --> 0!0 --> 1!-3943 --> 0
!(22 == 22) --> !1 --> 0
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.
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
If-Else Statementsif(expr) stmt1;else stmt2;
if(expr){ multiple stmts;}else{ multiple stmts;}
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");}
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;}
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;}
While Loops
while ( expr) stmt;
while (expr){ multiple stmts;}
While Loop Example
int i = 0; sum = 0;
while (i <= 10){ sum += i; i++;}
• Tracesum is 55i is 11
Sentinel Loopswhile(!sentinel){
do something}
• Example:
read input
while(strcmp(input, "-999") != 0){ do something read input again}
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';
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';}
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
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)
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;
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);
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
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;
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;
Loop tools
• break; //Takes you to the end of a loop
• continue; //Take you to the beginning of a loop
•
While loop examplewhile(true){ while(i < n) { if(i == 7) break; else if(i == 2) { i += 2; continue; } i++; } stmt; break;}
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");
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", ¤t); total += current; }
printf("%d is the total\n", total);
return 0;}
• Input:
12345
• Output:
15 is the total
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);
Another Example Continued
if(operator == 'q' || operator == 'Q') break; else if(operator == '+') result += value; else if(operator == '-') result -= value; else if(operator == '*') result *= value;
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;
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;}
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.
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");}
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
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 ...}
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) { ...}
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}
Example
int min(int a, int b){ if(a < b) return a; return b;}
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}
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;
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.
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));
Assertions
• To use assertions
#include <assert.h>
assert(expr);
• Ex. assert(a > 0);
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
Library File
• In your .c file
#include "program.h"
int min(int a, int b){ ...}
Main Function
• In main.c
#include "program.h”#include <stdio.h>
int main(...){ ... minval = min(a,b);}
Recommended