560 likes | 572 Views
This presentation covers the basics of programming, including variable types, arithmetic operators, conditional statements, iterative statements, arrays, and pointers. It provides examples and explanations to help beginners understand these concepts.
E N D
CECS 130Midterm Exam ReviewSpring 2019 Provided by REACH Presenter: Timi
To Download this presentation… • Go to http://reach.louisville.edu/examprep/CECS-TestReviews.html#cecs130
Variable Types • To declare and instantiate a constant (read only) value: • constint x = 20; • const float PI = 3.14;
Trivia Which syntax is correct? • int x; • printf(“Enter the value of x\n”); • A: scanf(“x = %d”, &x); • B: scanf(“x = %d”, x); • C: scanf(“x = “ + x); • int x = 1; • A: printf(“x = %d”, &x); • B: printf(“x = %d”, x); • C: printf(“x = “ + x);
Conversion Specifiers • Character - %c • Integer - %d • Float (decimal)- %f • String - %s • printf Format Tags: • Format: %[flags][width][.precision][length]specifier • Example: %[.precision]specifier float fboat = 12.123432; printf(“%.2f, %.3f, %d”, fboat, fboat, fboat);
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
Trivia Do you know the answer to these? • A. !( 1 | | 0 ) • B. !( 1 | | 1>0 && 0 ) • C. !(( 1 | | 1>0 ) && 0)
Answers: • A. !(1||0) !(1) 0 • B. !(1||1<0&&0) !(1||1<0)!(1||0)!(1)0 • C. !((1||1<0)&&0) !((1||0)&&0) !(1&&0) !(0)1
Conditionals/If-statements • These are used for making decisions when there are multiple possible outcomes • If-statement • If-else statement • If-else-if statement • Nested-if statement • Switch-case statement
Example • Using if statements, write a program that will ask a user to enter a number 1, 2 or 3 and print out the following based on the user input: • 1 She was number 1 • 2 Fool me twice, can’t put the blame on you • 3 Gimme 3 steps
Looping and iterative statements • These are used for repetitive tasks such as: • Counting • Going through a list of items • going through an array • Repeating the same task n-times • Types: • While statement • Do-while statement • For statement
While statement How it works Example • Initialize a value: inti = 0; • Test for a condition to be true: While(i < 10) • Perform some action on i or using i: Printf(“%d”, i); • Increment or decrement i such that each iteration takes it closer to making the condition false i++;
Do-While statement How it works Example • Initialize a value: inti = 0; • Perform some action on i or using i: Printf(“%d”, i); • Increment or decrement i such that each iteration takes it closer to making the condition false i++; • Test for a condition to be true: While(i < 10) • This will perform the action on i at least once
For-statement How it works Example • Initialize a value: inti = 0; • Test for a condition to be true: While(i < 10) • Increment or decrement i such that each iteration takes it closer to making the condition false i++; • Perform some action on i or using i: Printf(“%d”, i);
Break/Continue Statements • Break: 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 the 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
Function Prototypes and Definitions • Function Prototype Syntax • return-type function_name ( arg_type, ..., arg_type); • Function Prototypes tell you the data type returned by the function, the datatype of the function’s parameters, how many parameters it takes, and the order of parameters. • Function definitions implement the function prototype • A function may or may not have arguments
Trivia • Where are function prototypes located in the program? • Where do you find function definitions?
Arrays • An array is a collection of contiguous (physically next to each other) memory locations used to store homogenous data or data belonging to the same data type • How do you declare a one-dimensional array made up of 10 integers? Answer: intiArray[10] Declare the following 1-dimensional Arrays: • Array of type float with 1000000 elements • Array of type Boolean with 5 elements
Initializing an Array • An array can be initialized as follows: intarrayName[5] = {0, 1, 2, 3, 4}; • The length of an array == size of the array • The maximum index of an array is the length of the array – 1. Why? • Is it possible to use a looping statement to initialize an array?
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.
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.
Pointers…cont’d int val = 5; //variable declaration int *val_ptr = &val; //pointer declaration name: name: Value Value address: address: val_ptr val 0x3F 5 0x3F 0x83
Pointers…cont’d • 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_ptr name: val Value Value &val = 0x3F &val_ptr = 0x83 location: location: 0x3F 5
Pointers…cont’d • 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; }
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; }
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; printf(*x=%d, *y=%d”, *x,*y); } 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; printf(x=%d, y=%d”, x,y); } • Output: • *x = 5, *y = 3 • *x = 3, *y = 5 • a = 3, b = 5 • Output: • x = 5, y = 3 • x = 3, y = 5 • a = 3, b = 5
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.
Pointers to Arrays…cont’d intmain() { int list[3] = {10, 3, 5}; int k = 0; k = *list + 1; printf(“k = %d”, k); return 0; } Intmain() { int list[3] = {10, 3, 5}; int k = 0; k = *(list + 1); printf(“k = %d”, k); Return 0; } • Output: k = 11 • Output: k = 3
Data Structures - Structs • 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.
Trivia • Write a program to define a structure which contains details of a car - year, make, company and tag. Can you also create struct instances for all 4 cars using arrays, loops and structs? Car Year – 1994 – integer Make – Nissan – string Color – White – string Mileage – 21.22 – float Electric – Yes - Boolean
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
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; }
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()
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); fscanf(pRead, "%s", name); } //end loop return 0; }
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.
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); } }
Appending Data • pWrite = fopen("students.dat", "w"); • pWrite = fopen("hobbies.dat", "a");
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.