Presentation is loading. Please wait.

Presentation is loading. Please wait.

CECS 130 Mid-term Test Review

Similar presentations


Presentation on theme: "CECS 130 Mid-term Test Review"— Presentation transcript:

1 CECS 130 Mid-term Test Review
CECS 130 Midterm Exam Review, Spring 2018 CECS 130 Mid-term Test Review Provided by REACH – Resources for Academic Achievement Presenters: REACH Spencer Goff

2 To download this presentation…
Go to Make sure everyone signed in on the sign in sheet with their name and student ID number!

3 Variable Types Data Type Description initialization Example Integer Whole numbers, positive or negative int x = ; -3 , 0, 3 , 29 Floating-point number All numbers, positive or negative, decimals and fractions float x = ; , 0.00, Character Representations of integer values known as character codes char x = ‘ ’ ; m, To declare and instantiate a constant (read only) value: const int x = 20; const float PI = 3.14;

4 Variable Types TYPE SIZE VALUES bool true (1) or false (0) char
‘a’ to ‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int -2,147,483, to 2,147,483,647 short -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in a bool?

5 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int -2,147,483, to 2,147,483,647 short -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in a char?

6 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int -2,147,483, to 2,147,483,647 short -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in an int?

7 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int 4 bytes -2,147,483, to 2,147,483,647 short -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in a short?

8 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int 4 bytes -2,147,483, to 2,147,483,647 short 2 bytes -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in a long?

9 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int 4 bytes -2,147,483, to 2,147,483,647 short 2 bytes -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in a float?

10 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int 4 bytes -2,147,483, to 2,147,483,647 short 2 bytes -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double +- (2.3 x 10^ to x 10^308) How many bytes are in a double?

11 Variable Types TYPE SIZE VALUES bool 1 byte true (1) or false (0) char
‘a’ to‘z’ , ‘A’ to ‘Z’, ‘0’ to ‘9’, space, tab, etc. int 4 bytes -2,147,483, to 2,147,483,647 short 2 bytes -32, to 32,767 long -2,147,483, to 2,147,483,647 float + - (1.2 x 10^-38 to x 10^38) double 8 bytes +- (2.3 x 10^ to x 10^308)

12 Trivia time! Which syntax is correct? int x = 1;
A: printf(“x = %d”, &x); B: printf(“x = %d”, x); C: printf(“x = “ + x); Conversion specifiers (%d, %f, etc.) explained in next slide.

13 Trivia time! - Answer Which syntax is correct? int x = 1;
B: printf(“x = %d”, x); Conversion specifiers (%d, %f, etc.) explained in next slide.

14 Trivia time! Which syntax is correct? int y = 0;
printf(“Enter the value of y: \n”); A: scanf(“x = %d”, &x); B: scanf(“x = %d”, x); Conversion specifiers (%d, %f, etc.) explained in next slide.

15 Trivia time! - Answer Which syntax is correct? int y = 0;
printf(“Enter the value of y: \n”); A: scanf(“x = %d”, &x); Conversion specifiers (%d, %f, etc.) explained in next slide.

16 Conversion Specifiers
Character - %c Integer %d Float (decimal)- %f String - ????? printf Format Tags: Format: %[flags][width][.precision][length]specifier Example: %[.precision]specifier Output: 7 | float fboat = ; 8 | printf( “%.2f, %.3f, %.5f”, fboat, fboat, fboat ); 12.12, ,

17 Conversion Specifiers
Character - %c Integer %d Float (decimal)- %f String - %s printf Format Tags: Format: %[flags][width][.precision][length]specifier Example: %[.precision]specifier Output: 7 | float fboat = ; 8 | printf( “%.2f, %.3f, %.5f”, fboat, fboat, fboat ); 12.12, ,

18 Arithmetic, Logic and Order of Precedence
Operators Description ( ), !( ) Parentheses: evaluated from innermost to outermost *, /, % Multiplication: evaluated from left to right + , - Addition: evaluated from left to right <, <=, >, >= Inequalities: evaluated from left to right ==, != Equalities: evaluated from left to right &&, || Logical expressions: &&’s first, then ||’s. *This is a highly abbreviated list. See for the full order of precedence.

19 Predict the printout: User enters ‘2’ and ‘4’:
1 | #include <stdio.h> 2 | 3 | int main() 4 | { 5 | int iNum_1= 0; 6 | int iNum_2= 0; 7 | 8 | printf( “Please enter first number: ” ); 9 | scanf( “%d”, &iNum_1 ); // (user enters 2) 10| printf( “\nEnter second number: ” ); 11| scanf( “%d”, &iNum_2 ); // (user enters 4) 12| printf( “\n\n The result is %d. \n”, 24 / (iNum_1 * iNum_2) + 6 / 3); 13| 14| return 0; 15| } Answer: 5 (shown on next slide)

20 Predict the printout: User enters ‘2’ and ‘4’:
Output: Please enter first number: 2 Enter second number: 4 The result is 5. 1 | #include <stdio.h> 2 | 3 | int main() 4 | { 5 | int iNum_1= 0; 6 | int iNum_2= 0; 7 | 8 | printf( “Please enter first number: ” ); 9 | scanf( “%d”, &iNum_1 ); 10| printf( “\nEnter second number: ” ); 11| scanf( “%d”, &iNum_2 ); 12| printf( “\n\n The result is %d. \n”, 24 / (iNum_1 * iNum_2) + 6 / 3); 13| 14| return 0; 15| }

21 Can you predict the printout?
1 | #include <stdio.h> 2 | 3 | int main() 4 | { 5 | int x = 4; 6 | int y = 9; 7 | int result1, result2; 8 | 9 | result1 = y/x; 10| result2 = y%x; 11| 12| printf( “\n\n result1 is %d. result2 is %d \n”, result1, result2); 13| }

22 Can you predict the printout?
Output: result1 is 2. result2 is 1. 1 | #include <stdio.h> 2 | 3 | int main() 4 | { 5 | int x = 4; 6 | int y = 9; 7 | int result1, result2; 8 | 9 | result1 = y/x; 10| result2 = y%x; 11| 12| printf( “\n\n result1 is %d. result2 is %d \n”, result1, result2); 13| }

23 Conditions and Operators
Description == Equal to != Not Equal > Greater Than < Less Than >= Greater Than or Equal to Order of Precedence Description && AND condition || OR condition

24 Comparisons > greater than 5 > 4 is TRUE
< less than < 5 is TRUE >= greater than or equal 4 >= 4 is TRUE <= less than or equal 3 <= 4 is TRUE == equal to == 5 is TRUE != not equal to 5 != 4 is TRUE

25 Boolean Operators True = 1, False = 0 AND 1 && 1 -> True 1 && 0 -> False 0 && 1 -> False 0 && 0 -> False OR 1 || 1 -> True 1 || 0 -> True 0 || 1 -> True 0 || 0 -> False = !1 = 0 = !(1||0&&0) = !(1||0) = !1 = 0 = !((1||0)&&0) = !(1&&0) = !0 = 1 (shown in next slide)

26 Boolean Operators Do you know the answer to these? A. !( 1 | | 0 ) B. !( 1 | | 1>0 && 0 ) C. !(( 1 | | 1>0 ) && 0) = !1 = 0 = !(1||0&&0) = !(1||0) = !1 = 0 = !((1||0)&&0) = !(1&&0) = !0 = 1 (shown in next slide)

27 Boolean Operators Answers: A. B. C. !(1||0) =!(1) =0 !(1||1<0&&0)
=!(1||0&&0) =!(1||0) =!(1) =0 !((1||1<0)&&0) =!((1||0)&&0) =!(1&&0) =!(0) =1

28 Example Using if-statements, write a program (on paper!) that will ask a user to enter a number 1, 2 or 3 and print out the following: User Input Printout 1 He was Number 1! 2 Fool me 2 times, can’t put the blame on you. 3 Gimme 3 steps.

29 Example: 1 | #include <stdio.h> 2 | int main() {
4 | printf( “Enter one of the following: %d, %d, or %d\n”,1,2,3 ); 5 | scanf( “%d”, &a ); 6 | if(a==1||a==2||a==3) { 7 | if(a==1) 8 | printf(“\nSmitty Werbenjagermanjensen was Number %d.\n”, 1); 9 | if(a==2) 10| printf(“\nFool me %d times, can’t put the blame on you.\n”, 2); 11| if(a==3) 12| printf(“\dGimme %d steps.\n”, 3); 10| } 11| else 12| printf(“\nSorry, you entered an invalid value\n” ); 16| return 0;

30 Switch-Case Statement
1 | switch (var) 2 | { 3 | case 1: 4 | printf(“case 1 is executed”); 5 | break; //MUST have break, or program will continue running other cases 6 | case 2: 7 | printf(“case 2 is executed”); 8 | break; 9 | 10| default: 11| printf(“default case is executed”); 12| break; 13| }

31 The while( ) loop while ( condition )
{ Code to execute while the condition is true } 1 | #include <stdio.h> 2 | int main() 3 | { 4 | int x = 0; 5 | 6 | while ( x < 10 ) //the while loop will only execute if this condition is true 7 | { 8 | printf( “%d”, x ); 9 | x++; 10| printf(“\nFool me %d times, can’t put the blame on you.\n”, x); 11| } 12| getchar(); return 0; 13| } While loop is also known as an Entry Control loop

32 The do-while( ) loop while ( condition )
{ Code to execute while the condition is true } 1 | #include <stdio.h> 2 | int main() 3 | { 4 | int x = 0; 6 | do //NOTE: a do-while loop will ALWAYS execute at least once 7 | { 8 | printf( “%d:”, x ); 9 | x++; 10| printf(“\n Fool me %d times, can’t put the blame on you.\n”, x); 11| } while ( x < 10 ); 12| getchar(); return 0; } The (do-while loop) is known as an Exit Control loop Output -> 0: Fool me 2 times, can’t put the blame on you 1: Fool me 2 times, can’t put the blame on you 2: Fool me 2 times, can’t put the blame on you

33 The for( ) loop Often used when the # of iterations is already known.
Contains 3 separate expressions: Variable initialization Conditional statement Increment/Decrement 1 | #include <stdio.h> 2 | 3 | void main() 4 | { 5 | int x = 0; 6 | for( x=10; x>=0; x-- ) { 7 | printf( “%d\n”, x ); 8 | } 9 |}

34 Break/Continue Statements
Used to exit a loop. Once this statement is executed the program will execute the statement immediately following the end of the loop. continue; Used to manipulate program flow in a loop. When executed, any remaining statements in the loop will be skipped and the next iteration of the loop will begin. Q: Can you use a break inside of nested if statements? The “break” statements cannot be used in IF statements Can they be used inside nested-ifs?: Nope. They can be used only in loops

35 Break/Continue Statements
No. You cannot use break for nested ifs. Nested ifs are not loops, just conditional statements. The “break” statements cannot be used in IF statements Can they be used inside nested-ifs?: Nope. They can be used only in loops

36 Function Prototypes & Definitions
Function Prototype Syntax return-type function_name ( arg_type, ..., arg_type); Function Prototypes tell you the data type returned by the function, the data type of the function’s parameters, how many parameters it takes, and the order of parameters. Function definitions implement the function prototype Where are function prototypes located in the program? Where do you find function definitions? Purpose of functions: Code reusability. Ex: printf() command! For more explanation, see ATM example in Page 112 of the textbook.

37 Function Prototypes & Definitions
Where are function prototypes located in the program? Answer: before the main( ) { } function. Where do you find function definitions? Answer: function definitions are self-contained outside of the main( ) { } function, usually written below it.

38 Function Example Input: x = 2 y = 3 z = 4 #include <stdio.h>
int mult (int,int); // function prototype int main() { int x,y,z; printf( “\n x = "); scanf( "%d", &x ); printf( “\n y = ”); scanf( "%d", &y ); printf( “\n z = ”); scanf( "%d", &z ); printf( “\n x*y = %d\n", mult( x, y ) ); // function call printf( “\n z^2 = %d\n", mult( z, z ) ); // function call } int mult (int a, int b) { //function definition return a * b; Output shown in next slide

39 Function Example Output: x = 2 y = 3 z = 4 x*y = 6 z^2 = 16
#include <stdio.h> int mult (int,int); // function prototype int main() { int x,y,z; printf( “ x = " ); scanf( "%d", &x ); printf( “\n y = ”); scanf( "%d", &y ); printf( “\n z = ”); scanf( "%d", &z ); printf( “\n\n x*y = %d\n", mult( x, y ) ); // function call printf( “\n z^2 = %d\n", mult( z, z ) ); // function call } int mult (int a, int b) //function definition return a * b; Output: x = 2 y = 3 z = 4 x*y = 6 z^2 = 16

40 Function with void types
#include <stdio.h> void printReportHeader(); // function prototype int main() { printReportHeader(); // function call printf( “\n z^2 = %d\n", mult( z, z ) ); // function call return 0; } void printReportHeader() //function definition printf("\nColumn1\tColumn2\tColumn3\tColumn4\n");

41 Declaring a 1-D Array How do you declare a one-dimensional array made up of 10 integers? Answer: int iArray[10] Other array declarations: int iArray[10]; float fAverages[30]; double dResults[3]; short sSalaries [9]; char cName[19]; // 18 characters and 1 null character

42 Declaring a 1-D Array Why do we initialize variables? Because memory spaces may not be cleared from previous values when arrays are created. Can initialize an array directly. E.g.: int iArray[5]={0,1,2,3,4}; Can also initialize an array with a loop such as FOR( ) Challenge: Write a short program (on paper!) that uses a FOR loop to set each location of an array equal to a different value.

43 Declaring a 1-D Array: Solution
#include <stdio.h> main() { int x; int iArray[5]; for( x=0; x < 5 ; x++) { iArray[x] = x; }

44 Example: searching an array
#include <stdio.h> int main() { int x, iValue; int iFound = -1; int iArray[5]; // initialize the array for( x=0; x < 5 ; x++) { iArray[x] = ( x + x ); // array will = { 0, 2, 4, 6, 8 } } printf(“\n Enter positive integer to search for:”); scanf(“%d”, &iValue); // search for number for(x=0 ; x<5; x++) { if( iArray[x] == iValue) { iFound = x; break; if(iFound > -1) printf(“\n I found your search value in element %d \n”, iFound); else printf(“\n Sorry, your search value was not found \n”); return 0;

45 Pointers Pointer variables, simply called pointers, are designed to hold memory addresses as their values. Normally, a variable contains a specific value, e.g., an integer, a floating-point value, or a character. However, a pointer contains the memory address of another variable.

46 Pointer Syntax dataType *pointer_name = &variable_name;
(You can also initialize it “…= NULL;” or “… = 0;”) It’s important to initialize pointers to prevent fatal runtime errors or accidentally modifying important data.

47 Pointer Syntax Write code declaring an int and a pointer to that int.

48 5 0x3F Pointers int val = 5; //variable declaration
int *val_ptr = &val; //pointer declaration 5 val 0x3F name: 0x3F val_ptr 0x83 name: Value Value address: address:

49 Pointers When an ampersand (&) is prefixed to a variable name, it refers to the memory address of this variable. It is read as “address of”. name: val name: val_ptr 5 0x3F Value Value location: &val = 0x3F location: &val_ptr = 0x83

50 Ampersand example Output will be address of someChar
#include <stdio.h> int main() { char someChar = 'x'; printf(“%p\n", &someChar); return 0; } Output will be address of someChar There’s no way to know what the output will be. It’s the memory address of the variable.

51 Ampersand example Output will be: x #include <stdio.h>
int main() { char someChar = 'x'; printf(“%p\n", someChar); return 0; } Output will be: x There’s no way to know what the output will be. It’s the memory address of the variable.

52 Pointers When an asterisk (*) is prefixed to a variable name, it refers to the memory address of this variable. It is read as “value pointed to by”. main() { int a = 5; int *aPtr = &a; printf("value of a: %d \n", a); printf("address contained in aPtr: %p \n", aPtr); printf("value pointed to by aptr: %d \n", *aPtr); return 0; }

53 Changing variables with pointers
#include<stdio.h> int main() { int x = 5; int y = 10; int* iPtr = NULL; printf("\n iPtr points to: %p \n", iPtr); //assign memory address of y to iPtr iPtr = &y; printf("\n iPtr now points to: %p \n", iPtr); //change the value of x to the value pointed to by iPtr x = *iPtr; //sets the value of x equal to the value of y // * means 'value pointed to by' printf("\n The value of x is now: %d \n", x); //changes the value of the variable pointed to by iPtr (which is y) to 15 *iPtr = 15; printf("\n The value of y is now: %d \n", y); return 0; }

54 Changing variables with pointers

55 Passing variables with pointers
void exchange(int*, int*); main() { int a = 5; int b = 3; exchange(&a,&b); printf(“a = %d, b = %d”,a, b); //pass by reference void exchange(int *x, int *y) { printf(*x=%d, *y=%d”, *x,*y); int temp = *i; int *x = *y; int *y = temp; } void exchange(int, int); main() { int a = 5; int b = 3; exchange(a,b); printf(“a = %d, b = %d”,a, b); } //pass by value void exchange(int x, int y) { printf(x=%d, y=%d”, x,y); int temp = x; int x = y; int y = temp; Output: (1) x = 5, y = 3 (2) x = 3, y = 5 (3) a = 3, b = 5 Output: *x = 5, *y = 3 *x = 3, *y = 5 a = 3, b = 5

56 Pointers to Arrays An array variable without a bracket and a subscript represents the starting address of the array. An array variable is essentially a pointer. Suppose you declare an array of integer values as follows: int list[6] = {11, 12, 13, 14, 15, 16}; *(list + 1) is different from *list + 1. The dereference operator (*) has precedence over +. So, *list + 1 adds 1 to the value of the first element in the array, while *(list + 1) dereferences the element at address list[1] in the array.

57 Pointers to Arrays Output: k = 11 Output: k = 3 int main() {
int list[3] = {10, 3, 5}; int k = 0; k = *list + 1; printf(“k = %d”, k); return 0; } Int main() { int list[3] = {10, 3, 5}; int k = 0; k = *(list + 1); printf(“k = %d”, k); Return 0; } Output: k = 11 Output: k = 3 Order of Operations – the compiler will do addition after the pointer is replaced with it’s referenced value (in the left-hand case above, 10). That is, unless the addition is within parenthesis. In that case, given *(iArray+n), the pointer references the nth cell in iArray. Note, one and only one of the variables inside the parenthesis must be an array. Otherwise the compiler throws an error.

58 Pointers -- When to use Allows for arrays in C -- The name of an array only points to the address of the first memory location of that array, which ends in a null terminator ‘\0’ To reuse a variable in multiple places in a program and save space Dynamic memory allocation Order of Operations – the compiler will do addition after the pointer is replaced with it’s referenced value (in the left-hand case above, 10). That is, unless the addition is within parenthesis. In that case, given *(iArray+n), the pointer references the nth cell in iArray. Note, one and only one of the variables inside the parenthesis must be an array. Otherwise the compiler throws an error.

59 Strings Function Description strlen()
Returns numeric string length up to, but not including null character tolower() and toupper() Converts a single character to upper or lower case strcpy() Copies the contents of one string into another string strcat() Appends one string onto the end of another strcmp() Compares two strings for equality; returns < 0 if str1 comes before str2 in alphabetical order strstr() Searches the first string for the first occurrence of the second string Q: How do you arrange two given names in alphabetical order?

60 Strings #include <stdio.h> int main() {
char name1[] = "John Doe"; char name2[] = "Anna Bell"; char *ptr1 = name1; char *ptr2 = name2; printf("Original: \n %s, %s \n", ptr1, ptr2); if(strcmp(name1,name2) > 0) // str1 greater than str2 ptr1 = name2;//only with ptrs! ptr2 = name1;//else use strcpy } else // => str1 lower than str2 { printf("Do nothing"); } printf("\nAscending order: \n %s, %s \n", ptr1, ptr2); return 0; Output: Original: John Doe, Anna Bell Ascending order: Anna Bell, John Doe

61 Strings Output: The length of string 1 is 5
#include <stdio.h> #include <string.h> //notice this! int main() { char *str1 = "REACH"; char str2[] = "Tutoring"; char str3[10] = "Rocks!"; printf("\nThe length of string 1 is %d \n", strlen(str1)); printf("\nThe length of string 2 is %d \n",strlen(str2)); printf("\nThe length of string 3 is %d \n",strlen(str3)); return 0; } Output: The length of string 1 is 5 The length of string 2 is 8 The length of string 3 is 6

62 Strings Output: The name in lowercase is barbara bush
#include <stdio.h> #include <string.h> void convertL(char *); int main() { char name1[] = “Barbara Bush”; convertL(name1); return 0; } void convertL(char *str) int x; for ( x = 0; x <=strlen(str) ; x++){ str[x] = tolower(str[x]);} printf(“\nThe name in lowercase is %s\n”, str); Output: The name in lowercase is barbara bush

63 Strings #include <stdio.h> #include <string.h>
void convertL(char *); int main() { char name1[] = “Barbara Bush”; char name2[20]; name2 = name1; //What’s wrong with this? return 0; }

64 Strings #include <stdio.h> #include <string.h>
void convertL(char *); int main() { char name1[] = “Barbara Bush”; char name2[20]; strcpy(name2, name1); //correct method return 0; }

65 Data File Hierarchy Entity Description Bit Binary digit, 0 or 1
Smallest value in a data file Byte Eight bits Stores a single character Field Grouping of bytes i.e a word, social security number Record Grouping of fields a single row of information, student name, age, ID, GPA File Grouping of records separate fields in a record using spaces, tabs, or commas

66 Data Structures Arrays require that all elements be of the same data type. It is often necessary to group information of different data types. An example is a list of materials for a product. The list typically includes a name for each item, a part number, dimensions, weight, and cost. C and C++ support data structures that can store combinations of character, integer, floating point and enumerated type data. They are called - structs. Q: Write a program to define a structure which contains details of a car; year, make, company, and tag.

67 Struct Syntax - 1 struct oneCar //elements in a list of cars {
int year; char make[10]; char model[10]; char tag[10]; }; int main() struct oneCar* rentals = malloc(sizeof(struct onecar)); rentals.year = 2008; strcpy(rentals.make, "Honda"); strcpy(rentals.model, "Civic"); strcpy(rentals.tag, "AS2395"); printf("The Year: %d\n", rentals.year); printf("The Make: %s\n", rentals.make); printf("The Model: %s\n", rentals.model); printf("The Tag: %s\n", rentals.tag); getchar(); } Output: Year = 2008 Make = Honda Model = Civic Tag = AS2395 The blue box is an example of using the same struct for a different fleet of vehicles. In this case, the company wants to manage its company vans separately from the rental cars. This will apply even more once you start using classes/objects in C++ because they could then add more fields for the vans (mileage, driver, location) vs the rentals (current renter, damages incurred, rental rate, etc.). You don’t need to worry about that for now though.

68 Struct Syntax - 2 typedef struct oneCar //modification here {
int year; char make[10]; char model[10]; char tag[10]; }fleet; //modification here int main() fleet rentals; //modification here rentals.year = 2008; strcpy(rentals.make, "Honda"); strcpy(rentals.model, "Civic"); strcpy(rentals.tag, "AS2395"); printf("The Year: %d\n", rentals.year); printf("The Make: %s\n", rentals.make); printf("The Model: %s\n", rentals.model); printf("The Tag: %s\n", rentals.tag); getchar(); return 0; } Output: Year = 2008 Make = Honda Model = Civic Tag = AS2395 fleet vans; vans.year = 2008; strcpy(vans.make, "Ford"); strcpy(vans.model, "Transit"); strcpy(vans.tag, "BG8731"); The blue box is an example of using the same struct for a different fleet of vehicles. In this case, the company wants to manage its company vans separately from the rental cars. This will apply even more once you start using classes/objects in C++ because they could then add more fields for the vans (mileage, driver, location) vs the rentals (current renter, damages incurred, rental rate, etc.). You don’t need to worry about that for now though.

69 Struct Syntax -2 Cont... struct oneCar //elements in a list of cars
{ int year; char make[10]; char model[10]; char tag[8]; }fleet; //for short we’ll call it a fleet int main() { fleet rentals[5]; // five cars that we rent out to clients rentals[0].year = 2008; strcpy(rentals[0].make, “Honda”); strcpy(rentals[0].model, “Element”); strcpy(rentals[0].tag, “AS2395”); […] rentals[4].year = 2015; strcpy(rentals[4].make, “Tesla”) strcpy(rentals[4].model, “Model S”); strcpy(rentals[4].tag, “2FST4U”); return 0; fleet vans[3]; //company vans vans[0].year = 2012; strcpy(vans[0].make, “Ford”); strcpy(vans[0].model, “EcoVan”); strcpy(Vans[0].tag, “MV1NUP”); […] Upto 3 different cars The blue box is an example of using the same struct for a different fleet of vehicles. In this case, the company wants to manage its company vans separately from the rental cars. This will apply even more once you start using classes/objects in C++ because they could then add more fields for the vans (mileage, driver, location) vs the rentals (current renter, damages incurred, rental rate, etc.). You don’t need to worry about that for now though.

70 Opening and Closing Files
Opening a data file should always involve a bit of error checking and/or handling. Failure to test the results of a file-open attempt will sometimes cause unwanted program results in your software. r for reading from a file, w for writing (AKA replacing the contents of) a file, a for appending data to a file

71 Opening and Closing Files
#include <stdio.h> int main() { FILE *pRead; \\File pointer pRead = fopen("file1.dat", "r"); if ( pRead == NULL ) printf("\nFile cannot be opened\n"); else printf("\nFile opened for reading\n"); return 0; }

72 Reading Data To read a data file, you need to know
how to read a file’s contents fscanf() check for the file’s EOF (end-of-file) marker feof()

73 Reading Data #include <stdio.h> int main() { FILE *pRead;
char name[10]; pRead = fopen("names.dat", "r"); if ( pRead == NULL ) printf("\nFile cannot be opened\n"); else printf("\nContents of names.dat\n\n"); fscanf(pRead, "%s", name); while ( !feof(pRead) ) printf("%s\n", name); } //end loop return 0; }

74 Writing Data Writing information to a data file you can use a function similar to printf() called fprintf() It uses a FILE pointer to write data to a file.

75 Writing Data #include <stdio.h> main() { FILE *pWrite;
char fName[20]; char lName[20]; char id[15]; float gpa; pWrite = fopen("students.dat", "w"); if ( pWrite == NULL ) printf("\nFile not opened\n"); else printf("\nEnter first name, last name, id and GPA\n\n"); printf("Enter data separated by spaces: "); scanf("%s%s%s%f", fName, lName, id, &gpa); fprintf(pWrite, "%s\t%s\t%s\t%.2f\n", fName, lName, id, gpa); fclose(pWrite); }

76 Appending Data pWrite = fopen("students.dat", "w");
pWrite = fopen("hobbies.dat", "a");

77 Dynamic Memory Allocation
Dynamic memory allocation allows your program to obtain more memory space while running, or to release it if it's not required. For example, instead of creating an array of a fixed size, you may create one that can expand as needed.

78 Dynamic Memory Allocation

79 Dynamic Memory Allocation
Malloc ptr = (int*) malloc(100 * sizeof(int)); Calloc ptr = (float*) calloc(25, sizeof(float)); Realloc ptr = realloc(ptr, newsize); Free free(ptr);

80 Dynamic Memory Allocation
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero. If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using realloc().

81 Malloc/free example #include <stdio.h> #include <stdlib.h> int main() { int num, i, *ptr, sum = 0; printf("Enter number of elements: "); scanf("%d", &num); ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc if(ptr == NULL) { printf("Error! memory not allocated."); exit(0); } printf("Enter elements of array: "); for(i = 0; i < num; ++i) { scanf("%d", ptr + i); sum += *(ptr + i); } printf("Sum = %d", sum); free(ptr); return 0; } }

82 Realloc() example #include <stdio.h> #include <stdlib.h> int main() { int *ptr, i , n1, n2; printf("Enter size of array: "); scanf("%d", &n1); ptr = (int*) malloc(n1 * sizeof(int)); printf("Address of previously allocated memory: "); for(i = 0; i < n1; ++i){ printf("%u\t",ptr + i); } printf("\nEnter new size of array: "); scanf("%d", &n2); ptr = realloc(ptr, n2); for(i = 0; i < n2; ++i) printf("%u\t", ptr + i); return 0; } }

83 On the test… Some types of problems you will likely encounter:
True/False questions Fill-in-the-blanks questions Finding errors in programs Common mistakes on this test: Not appending lines of code with a semicolon (“;”) Forgetting to use semicolons when writing a FOR loop Forgetting the order of the parts of a FOR loop Forgetting to add an ampersand (“&”) to your variable parameter in SCANF functions (and mistakenly using the ampersand when using PRINTF) Mixing up * and & in general. Off-by-one errors when accessing an array, especially when using a FOR loop.

84 Test Success: The Night Before
Avoid Extensive Study Only Do a Brief Review Do Something Relaxing Get Plenty of Sleep Avoid Stress-Producing Situations Maintain a Positive Attitude

85 Test Success: Day of the Test
Get Off to a Good Start Arrive on Time (or Early!) Compose Yourself Do a Final Scan of Your Notes Maintain a Confident Attitude Eat breakfast if possible. Compose yourself = deep breaths, calm yourself, get super angry, whatever. Just get in your best test-taking state of mind. comic by KC Green (

86 But seriously, you all will do great.
Thanks for coming, and good luck! (If you have not signed in, please do so before you leave!) This presentation was provided by REACH – Resources for Academic Achievement Make sure everyone signed in on the sign in sheet with their name and student ID number!

87 To download this presentation…
Go to Make sure everyone signed in on the sign in sheet with their name and student ID number!


Download ppt "CECS 130 Mid-term Test Review"

Similar presentations


Ads by Google