60
https://ucfstudyunion.wordpress.com/computer-science/ Study Union: Spring 2021 Supplemental Instruction COP 3223C (Dr. Ahmed) w/ Alan :) Topics that we will cover: Course Introduction o How is C different to that of other languages? o Who are the creators of the C language and what did they make with it? o How does the computer read code similar to how we read as humans? Where does it start reading and stop? Relationship between chapters and functions? Relationship the termination of sentences in C and reading? o What can you make with the C language? o What are preprocessor Headers? o What is int main()? o How do you make multi-line comments and single line comments? Printf()/Scanf() o How does printf() help you output something on the screen? o Arguments of printf() o Special Characters o What is scanf() and what is the format of it? Variables o Types of variables o Limits to variables o How variables are stored in the memory o Global variables o What are format specifiers and what do they do? o What are the different format specifiers depending on the type of variable? 1

Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Study Union: Spring 2021 Supplemental Instruction COP 3223C (Dr. Ahmed) w/ Alan :)

Topics that we will cover:

Course Introductiono How is C different to that of other languages?o Who are the creators of the C language and what did they make with it?o How does the computer read code similar to how we read as humans?

Where does it start reading and stop? Relationship between chapters and functions? Relationship the termination of sentences in C and reading?

o What can you make with the C language? o What are preprocessor Headers?o What is int main()?o How do you make multi-line comments and single line comments?

Printf()/Scanf()o How does printf() help you output something on the screen?o Arguments of printf()o Special Characterso What is scanf() and what is the format of it?

Variableso Types of variableso Limits to variableso How variables are stored in the memoryo Global variableso What are format specifiers and what do they do?o What are the different format specifiers depending on the type of variable?

Calculations and Operatorso Arithmetic Operators

+, -, *, /, %, ++, -- o Relational Operators

==, !=, >, <, >=, <=o Logical Operators

&&, ||, !

1

Page 2: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Functions / Function with Parameterso What are functions?o What is the importance of function prototypes?

How does it help prevent errors?o Return value of a function (type in front of function)o How do you store return value of function?o How do you pass in arguments?o What is void?o What is the scope of variables?

Pointerso What are pointers?o How to declare a pointer?o How is it useful in programming?o How to dereference a pointer?

Arrayso What are arrays?o How do you declare an array?o What are strings?o The dirty truth about arrays?o How do pointers relate to arrays and how can you pass an array to a function?

Two Dimensional Arrayso What are two-dimensional arrays?o How are they different from one-dimensional arrays?o How do they relate to pointers?o What are String arrays?o How do string arrays relate to two-dimensional arrays?

For Loopso How do you declare a for loop?o What is a for loop used for?

While / Do While Loopso How do you declare a while loop?

2

Page 3: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o What is a while loop used for? o What is a do while loop?

Conditionals o What are if statements used for?o How do you declare an if… else chain?o If() -> else if() -> elseo Logical OR (||) and Logical AND (&&) and Logical NOT (!=)

Conditionals (also switch)o What are switch statements?o Declaration of switch statementso Characters o Numberso Can you use switch for strings?o Importance of break;o Fall through in absence of break

Data Structureso What are structures?o Structure Members?o Pointer to a structureo Dereferencing a structure member

File I/Oo What is File I/O?o What are the different modes of File I/O?o How do you open a file?o How do you read from a file?o How do you write into a file?o How do you close a file?

Bits and Byteso How do you print out a hexadecimal value?o How to turn decimal into Binary?o How to turn in binary into Decimal?o AND Operator (&)o OR Operator (|)o XOR Operator (^)o NOT Operator (~)

3

Page 4: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Dynamic Memory Allocationo What is the difference between dynamic and static memory allocation?o What header file should be included to use the functions for dynamic memory?o What are the different functions that can be used to dynamically allocate

memory?

Linked Listo What is a linked list?o How is a linked list declared?o What is the purpose of a head node and a current node?o What are some header files that should be included before the start of the code?

Recursiono What is recursion? o Why is recursion useful?o When should recursion end?

4

Page 5: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Table of ContentsCourse Introduction......................................................................................................................................................................................................7

Exercise................................................................................................................................................................................................................................ 8

Printf()/Scanf()..............................................................................................................................................................................................................9

Exercise:............................................................................................................................................................................................................................. 10Solution:.......................................................................................................................................................................................................................................................................................................... 11

Variables.....................................................................................................................................................................................................................12

Exercise:............................................................................................................................................................................................................................. 15Solution:.......................................................................................................................................................................................................................................................................................................... 15

Exercise:............................................................................................................................................................................................................................. 17

Functions / Functions with Parameters......................................................................................................................................................................18

Exercise:............................................................................................................................................................................................................................. 19Solution:.......................................................................................................................................................................................................................................................................................................... 20

Pointers.......................................................................................................................................................................................................................21

Exercise:............................................................................................................................................................................................................................. 22Solution:.......................................................................................................................................................................................................................................................................................................... 23

Arrays..........................................................................................................................................................................................................................24

Exercise:............................................................................................................................................................................................................................. 25Solution:.......................................................................................................................................................................................................................................................................................................... 25

Exercise 2:.......................................................................................................................................................................................................................... 26Solution:.......................................................................................................................................................................................................................................................................................................... 27

Two Dimensional Arrays.............................................................................................................................................................................................28

For Loops....................................................................................................................................................................................................................29

Exercise:............................................................................................................................................................................................................................. 30Solution:.......................................................................................................................................................................................................................................................................................................... 30

While Loops/ Do While...............................................................................................................................................................................................31

........................................................................................................................................................................................................................................... 32

Exercise:............................................................................................................................................................................................................................. 33Solution:.......................................................................................................................................................................................................................................................................................................... 33

Conditionals................................................................................................................................................................................................................34

Exercise:............................................................................................................................................................................................................................. 35Solution:.......................................................................................................................................................................................................................................................................................................... 35

Conditionals (also switch)...........................................................................................................................................................................................36

Exercise:......................................................................................................................................................................................................................37Solution:.......................................................................................................................................................................................................................................................................................................... 37

Data Structures...........................................................................................................................................................................................................38

Exercise:............................................................................................................................................................................................................................. 39Solution:.......................................................................................................................................................................................................................................................................................................... 39

File I/O........................................................................................................................................................................................................................40

Exercise.............................................................................................................................................................................................................................. 41

Make a text file hello.txt and ouput the string “hello world” into the text file. Then read from that text file and output the file contents.........................41

Bits and Bytes..............................................................................................................................................................................................................42

.....................................................................................................................................................................................................................................44

Dynamic Memory Allocation......................................................................................................................................................................................45

Exercise.............................................................................................................................................................................................................................. 46

Linked List...................................................................................................................................................................................................................47

Recursion.....................................................................................................................................................................................................................48

Exercise.............................................................................................................................................................................................................................. 48

References/Useful Links..............................................................................................................................................................................................49

5

Page 6: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Table of FiguresFigure 1: Special Characters..........................................................................................................................................................................................9

Figure 2: Types of Variable with Ranges....................................................................................................................................................................12

Figure 3: ASCII - American Standard Code for Information Exchange.....................................................................................................................12

Figure 4: Format Specifiers List..................................................................................................................................................................................13

Figure 5: Array Pictorial Representation.....................................................................................................................................................................24

Figure 6: For Loop Pictorial Representation...............................................................................................................................................................28

Figure 7: While Loop Pictorial Representation...........................................................................................................................................................30

Figure 8: Do While Loop Flow Diagram....................................................................................................................................................................31

6

Page 7: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Course Introductiono How is C different to that of other languages?

Unlike other languages, C is a very low-level language that you basically have to give all the instruction that it has to do. Additionally, it is a static language unlike a dynamic language, once you set the variable type it has to stay that type throughout the entirety of the code.

* Important: C is case sensitive so int race_car1; is different than Race_car1;

o Who is the creator of the C language and what did he/she make with it?o The creator the C language is Dennis Ritchie. He made in 1972 in

the Bell Telephone laboratories. He used it to create the UNIX operating system and B language with Ken Thompson.

o How does the computer read code similar to how we read as humans? Where does it start reading and stop? Relationship between chapters and functions? Relationship the termination of sentences in C and reading?

o The computer reads code similar to how humans read a book. The computer reads code from left to right and from top to bottom. The computer starts reading code from intmain() and moves to other functions in chronological order similar to how humans start reading from chapter 1 and move on to subsequent chapters in chronological order. The termination of a “sentence” in code ends with a semicolon (;) while sentences in reading end with a period (.)

o What can you make with the C language? The C language is used to make operating systems like Mac OS and

basically any UNIX based operating systems like Ubuntu or Devian. It is also used to make basic programs on the computer like Kindle Books, VLC, etc. Additionally, it is also used to make executable files which can be a bad thing (viruses).

o What are preprocessor Headers?o Preprocessor is basically a process which tells the compiler to do

pre-processing before the actual compiling. Headers are basically files that the computer finds, reads, and processes and essentially replaces all the file contents in place of where the #include header file is. When you download a compiler for C it will already have header files which will have many widely used functions.

#include <stdio.h> stands for standard input and ouput; this will have functions like scanf(), printf(), fseek(), etc.

#include <stdlib.h> stands for standard library; this will have functions like malloc(), free(), rand()

7

Page 8: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o What is int main()? int main() is the first function that the compiler will go to after doing all

preprocessor commands and defining constants. int main(void) and int main() are the same thing. What is inside of the parentheses are the arguments of the function so leaving it blank means no arguments and putting void essentially means get rid off so it also means no arguments. The primary purpose of int main() is that it gives a unified place where code starts for everyone like Chapter 1 is the first chapter that you start on. At the end of int main() it should return 0 which basically tells the program to end and that the program ran successfully.

o How do you make multi-line comments and single line comments? Comments are ignored by the computer and are useful for writing

observations or explanations within the code. Single line comments are made with two forward slashes and the comment

right after it. Multi-Line comments are made with first an opening forward slash and asterik

and then an asterik and forward slash at the very end to indicate where it ends.

ExerciseOutput “Hello World” and demonstrate how to use single-line and multi-line comments

#include <stdio.h>

// This is a single line comment

/*This is a multiple linecomment*/

int main(void) {

printf("Hello World\n"); return 0;

}

8

Page 9: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Printf()/Scanf()o How does printf() help you output something on the screen?o Arguments of printf()o Special Characterso What is scanf() and what is the format of it?

The format of printf() is printf(“Hello my name is %d”, variable); The first argument is what you are printing with format specifiers which will

get replaced by variables that you pass through. The format of scanf() is scanf(“ %s”, &Variable); The first argument of scanf is the type of variable that you will be passing

through, the second argument is the variable’s address where the computer needs to store the input into that variable.

Figure 1: Special Characters

9

Page 10: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Exercise:What is the output of this code? What is wrong with this code? #include <stdio.h>

int main() {

char favorite_letter;char second_favorite_letter;

printf("What is your favorite letter?\n"); scanf("%c", &favorite_letter);

printf("What is your second favorite letter?\n");scanf("%c", &second_favorite_letter);

printf("Your favorite letter is %c. Your second favorite letter is %c", favorite_letter, second_favorite_letter);

return 0;}

Solution: Special Characters! The code will only output the user’s favorite letter and not the second

favorite letter. The enter key actually has a special character that is associated with it -> newline (\n). In the code, it first asks the user for their favorite letter, the user enters their favorite number and then clicks the enter key. The enter key is now in the buffer (place in the computer where all the inputs of the user reside), now when the code asks for the user’s second favorite letter the enter key which still resides the buffer will get stored in the second_favorite_letter variable. Therefore, the second_favorite_letter will store “\n”.

To fix this issue you can actually tell the scanf() to ignore incoming whitespace (newline (\n), tab (\t) and spaces). By formatting scanf() in this way: scanf(“ %c”, &variable);

This is the way that most good programmers use scanf() and it’s good programming practice. They always format their scanf with a space before their format specifier.

10

Page 11: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Fixed Code:#include <stdio.h>

int main() {

char favorite_letter;char second_favorite_letter;

printf("What is your favorite letter?\n"); scanf(" %c", &favorite_letter);

printf("What is your second favorite letter?\n");scanf(" %c", &second_favorite_letter);

printf("Your favorite letter is %c. Your second favorite letter is %c", favorite_letter, second_favorite_letter);

return 0;}

An alternate method is to write a variable which will store the incoming whitespace in this way: scanf(“%c”, &favorite_letter);

scanf(“%c”, &enter_key); scanf(“%c”, &second_favorite_letter);

The only problem with this format is that it will only work if the only whitespace that they input is the enter key after entering the favorite letter. If they input the space bar and then the enter key for favorite letter it will not work (the space bar will get stored in enter_key and the enter key will get stored in second favorite letter.

11

Page 12: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Variableso Types of variableso Limits to variableso How variables are stored in the memoryo Global variableso What are format specifiers and what do they do?o What are the different format specifiers depending on the type of variable?

12

Figure 2: Types of Variable with Ranges

Page 13: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Figure 3: ASCII - American Standard Code for Information Exchange

13

Page 14: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Figure 4: Format Specifiers List

Variables are not just stored randomly in the memory! They are stored in specific places of your computer’s memory. You can access those places in the memory with pointers. Global Variables are defined in the preprocessor #define HELLO 1. It is good programming practice to define them through all uppercase letters.

Each character actually corresponds to a decimal number so you can actually use characters and numbers Interchangeably.

Characters are defined in the following way: char name = ‘C’; Format specifiers basically define the type of variable to be acquired on the standard

input/ouput for specific functions. For certain functions, you the computer needs to know the type and you pass in those variables through format specifiers. Ex. Scanf() and printf().

Exercise:Print out the decimal value of the char ‘A’ in programming.

Solution:

#include <stdio.h>

int main() {char name = 'A';

printf("%d", name);

return 0;}

14

Page 15: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Calculations and Operatorso Arithmetic Operators

+, -, *, /, %, ++, -- o + is additiono - is subtractiono * is multiplicationo / is divisiono % is modulus. The output is the remainder of the two numbers

you’re dividing. Ex. 11 % 2 = 1;

o ++ is increment operator. The operator increases a variable by one. Ex. x++ -> x = x +1;

o -- is decrement operator. The operator decreases a variable by one. Ex. x-- -> x = x – 1;

o Relational Operators ==, !=, >, <, >=, <=

o == is equality operator. Checks whether two values are equal. Ex. 1 == 2 -> False

o != is the opposite of equality operator. Checks whether two values are not equal.

Ex. 1 != 2 -> Trueo > is greater than operant

15

Page 16: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o < is less than operanto >= is greater than or equal to operanto <= is less than or equal to operant

o Logical Operators &&, ||, !

o Please see the section “Conditionals”

Exercise:What is the output of this piece of code, and how would you get the “true” output?#include <stdio.h>

int main(void) { int x = 1; int y = 2; float z = 0; z = x / y; printf("The value of z is %f", z); return 0;}

/* The output for this piece of code is “The value of z is 0.000000”This is because x and y are both integers and when you divide them together it cuts out the decimal part i.e., 0.5 becomes 0.0000In order to fix this code all, you would have to do is turn x and y into floats*/

16

Page 17: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Functions / Functions with Parameterso What are functions?o What is the importance of function prototypes? o How does it help prevent warnings?o Return value of a function (type in front of function)o How do you store return value of function?o How do you pass in arguments?o What is void?o What is the scope of variables?

A function is basically a group of statements that are all consolidated together in chronological order in order to accomplish a certain task or return something at the very end.

In Programming with C, functions should be declared before the call of any functions. The way that C works is that after doing all preprocessor instructions it will automatically start looking for the intmain() function. Now when you call a function in intmain() without having previously declared it doesn’t understand what that function is since it has no previous knowledge of the function. That’s why some compilers will give you an error without function prototypes. Don’t worry though function prototypes are easy to create! All you have to do is program that you usually do and at the very end put the functions that you used with the

17

Page 18: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

return type and arguments at the top of your code after the preprocessor commands. It’s easy and it’s good programming practice!

The return type of the function is what type of variable will be returned back into the function that you called it from. What gets returned back can be stored into a variable as long as you set it equal to the function that you call. For example: my_var = my_function(my_argument_1, my_argument_2). Recusion is the process where you call the same function within the same function and end the cycle until a certain condition is met.

Arguments are easily passed into the function in the format shown above my_var = my_function(my_argument_1, my_argument_2). Void is basically the same thing as leaving the arguments that you are passing through blank void essentially means no arguments.

Exercise:Create a function prototype for the following code:What would happen if you tried to use the variable declared in int main() in ice_cream_function()?

#include <stdio.h>

int main() {

int vanll_ice_creams;int choc_ice_creams;int total;

printf("How many vanilla ice creams did you eat yesterday?\n");scanf(" %d", &vanll_ice_creams);

printf("How many chocolate ice creams did you eat yesterday?\n");scanf(" %d", &choc_ice_creams);

18

Page 19: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

total = ice_cream(vanll_ice_creams, choc_ice_creams);

printf("You ate a total of %d ice creams. Stop eating so much ice cream and eat some spinach instead!", total);

return 0;}

int ice_cream(int vanilla, int chocolate) { int sum; printf("You ate %d vanilla ice creams!\n", vanilla); printf("You ate %d chocolate ice creams!\n", chocolate);

sum = vanilla + chocolate;

return sum;

}Solution: #include <stdio.h>

int ice_cream(int vanilla, int chocolate);

int main() {int vanll_ice_creams;int choc_ice_creams;

...return 0;}

int ice_cream(int vanilla, int chocolate) { int sum; ...

19

Page 20: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

return sum;}

Pointerso What are pointers?o How to declare a pointer?o How is it useful in programming?o How to dereference a pointer?

Pointers are special variables that hold the memory addresses of other variables. Why should you care? Having the memory address of another variable can actually be very useful in programming.

For one, as we’ll see in the “Arrays” section you can’t actually pass through a whole array at once in programming. Instead you have to pass through the pointer which holds the memory address of the array. You can also change the value of a specific variable in other functions which you couldn’t do otherwise.

In order to declare a pointer, you have to declare what type of variable it will be pointing to for example (if it’s going to point to an integer value) the ampersand refers to the memory address of the variable that it’s going to point to:

o int * my_pointer = &variable;

Good programming practice dictates that when you declared pointers, they have a capital ‘P’ before the variable name in order to indicate that it is a pointer: int * Pvariable

20

Page 21: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Dereferencing a pointer refers to getting the value of the variable that the pointer is pointing to. In order to deference a variable if the pointer “Pvariable” was pointing to variable x. It would be dereferenced in this way:

o *(Pvariable)

Exercise:Make a pointer that points to the variable that refers to the number of vanilla ice creams. Use this to dereferenced pointer to print out the value of the variable. Also use this pointer to change the value of the vanialla variable in the ice_cream function. Change it to 25.

#include <stdio.h> int ice_cream(int vanilla, int chocolate);

int main() {

int vanll_ice_creams;int choc_ice_creams;int total;

printf("How many vanilla ice creams did you eat yesterday?\n");scanf(" %d", &vanll_ice_creams);

printf("How many chocolate ice creams did you eat yesterday?\n");scanf(" %d", &choc_ice_creams);

total = ice_cream(vanll_ice_creams, choc_ice_creams);

21

Page 22: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

printf("You ate a total of %d ice creams. Stop eating so much ice cream and eat some spinach instead!", total);

return 0;}

int ice_cream(int vanilla, int chocolate) { int sum; printf("You ate %d vanilla ice creams!\n", vanilla); printf("You ate %d chocolate ice creams!\n", chocolate);

sum = vanilla + chocolate;

return sum;

}Solution:#include <stdio.h> int ice_cream(int vanilla, int chocolate, int * Pvanilla2);

int main() {

int vanll_ice_creams;int choc_ice_creams;int total;int * Pvanilla;

Pvanilla = &vanll_ice_creams;

printf("How many vanilla ice creams did you eat yesterday?\n");scanf(" %d", &vanll_ice_creams);printf("You ate %d vanilla ice creams!\n", *(Pvanilla));

printf("How many chocolate ice creams did you eat yesterday?\n");scanf(" %d", &choc_ice_creams);

total = ice_cream(vanll_ice_creams, choc_ice_creams, Pvanilla);

22

Page 23: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

printf("You ate %d vanilla ice creams now!\n", vanll_ice_creams);printf("You ate a total of %d ice creams. Stop eating so much ice cream and eat some spinach instead!", total);return 0;}

int ice_cream(int vanilla, int chocolate, int * Pvanilla2) { int sum;

*(Pvanilla2) = 25;

sum = vanilla + chocolate;

return sum; }

Arrayso What are arrays?o How do you declare an array?o What are strings?o The dirty truth about arrays?o How do pointers relate to arrays and how can you pass an array to a function?

Arrays are data structures of contiguous blocks of memory that hold the same type of variable in each of its elements.

o type arrayName[arraySize];

An integer array is declared like this:o int array[5] = {5,8,4,2,7}; OR... int array[];

Strings are actually just an array of characters grouped together like this:o char name[5] = “Alan”; OR... char name[];

Each string ends with a special character “\0” which is the null character which indicates the end of the string. So in reality, the array for char name[5] is stored as “Alan\0.” That’s why the array size is 5 instead of 4 to take into account the null character \0.

In order to change the value of a character array mid-code you have to change it using the built-in function (<string.h>). strcpy(destination, what will be copied);

23

Page 24: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Each element of an array has an index or number corresponding to it. The index starts counting from zero such that in the example above index 0 corresponds to the number 5 but index 3 corresponds to the number 4.

o You can access each element through the following: array[0] would hold the value 5 & array[3] would hold the value 4.

The dirty truth about arrays is that they are actually disguised as pointers. Believe it or not array is actually a pointer to the memory address to the first element of the array.

o &array[0] is equivalent to (array) AND, array[0] is equivalent to *(array+0)o &array[1] is equivalent to (array+1) AND, array[1] is equivalent to *(array+1)o &array[2] is equivalent to (array+2) AND, array[2] is equivalent to *(array+2)o &array[3] is equivalent to (array+3) AND, array[3] is equivalent to *(array+3)o ...

You can’t actually pass a whole array through a function so you pass the memory address of the first element of the array in the argument of the function. This has two dual benefits

o 1. You have the memory address of each element of the array.o 2. You have and can change the value of element of the array by dereferencing the

array pointer.

Exercise: What is wrong this code?What can you do to fix it?#include <stdio.h>

int main() {

char name[99];

printf("What is your full name?\n"); scanf("%s", name);printf("Your full name is %s", name);

return 0;}

24

Figure 5: Array Pictorial Representation

Page 25: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Solution:The code will actually think the spacebar is the end of the string so therefore it will only get the first name and not the last. Thus, you should split it up between two strings such that it will be in terms of first and last name. int main() {char first_name[99];char last_name[99];

printf("What is your first and last name?\n"); scanf(" %s", first_name);scanf(" %s", last_name);

printf("Your full name is %s", name);

return 0;}

Exercise 2: Pass the pointer of the array to function, and then change the value of the 4th index to 65. Then print out that value in intmain()

#include <stdio.h> int changearray(int * Parray);

int main() {

int array[5] = {5,8,4,2,7};

printf("The value of index 4: array[4] = %d\n", array[4]);// WRITE CODE HERE

printf("The value of index 4: array[4] = %d\n", *(array+4));

return 0;}

int changearray(int * Parray) { // WRITE CODE HERE return 0;

25

Page 26: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

}

Solution:#include <stdio.h> int changearray(int * Parray);

int main() {

int array[5] = {5,8,4,2,7};

printf("The value of index 4: array[4] = %d\n", array[4]);changearray(array);

printf("The value of index 4: array[4] = %d\n", *(array+4));

return 0;}

int changearray(int * Parray) { *(Parray+4) = 65; return 0;}

26

Page 27: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Two Dimensional Arrayso What are two-dimensional arrays?o How are they different from one-dimensional arrays?o What are String arrays?o How do string arrays relate to two-dimensional arrays?

Two dimensional arrays are essentially an array of an arrays. They can be thought of a matrix or table that is mxn size. It can be thought as a table with m rows and n columns. Don’t forget that the first index starts at zero for both the row and the column. It has similar properties to that of a one-dimensional array.

The integer, float, double, and other numerical datatype declarations are formatted:

o datatype arrname[size1][size2] = { {x_1,x_2,x_3,x_4,... nth}{j_1,j_2,j_3,j_4...kth};...}

String Arrays are an array of strings (character arrays). Strings are letters that are arranged together in a certain order like words.

A string array is declared in this format:o char arrname[size1][size2] = {

“Josh”“Table”

27

Page 28: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

“Shirt”...}

To access a specific element all one has to do is type the name of the array with its specific indexes such as

car[1][2]

For Loopso How do you declare a for loop?o What is a for loop used for?

The declaration for a for loop is: for (initialization; condition; increment) {

code;}

The for loop is mostly used when you have a set amount of times that you want to run the same piece of code multiple times in a row.

28

Page 29: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Figure 6: For Loop Pictorial Representation

Exercise:Print the value of variable ‘z’ from 64 to 69 using a for loop with a newline in between.

Solution:#include <stdio.h>

int main() { int z;

for(z=64; z<=69; z++) {

29

Page 30: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

printf("Value of z: %d \n", z); }

return 0;}

While Loops/ Do Whileo How do you declare a while loop?o What is a while loop used for?o What is a do while loop?

The declaration for a while loop is: o while(condition) {

code;}

The while loop is mostly used when you have a code that you want to run as long as a certain condition is met.

30

Page 31: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

The declaration for a do while loop is:o do {

code;} while(condition);

A do while loop does the same thing as a while loop but is different from that of a while loop because it will always run at least once. In addition, the conditional statement can be found at the bottom instead of at the top.

31

Figure 7: While Loop Pictorial Representation

Page 32: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Figure 8: Do While Loop Flow Diagram

Exercise: Print the value of variable ‘z’ from 64 to 69 using a while loop with a newline in between (Same as the for loop exercise but this time it’s with a while loop). Also do the same thing with a do while loop.

Solution:// With a while loop:#include <stdio.h>

32

Page 33: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

int main() { int z = 64;

while(z<=69) { printf("Value of z: %d \n", z); z++; }

return 0;}

// With a do while loop:int main(void) { int z = 64;

do { printf("Value of z: %d \n", z);

z++; } while (z<=69);

return 0;}

* This shows that you can essentially do the same thing for the for loop with a while loop for the majority of cases! It’s up to you really!

Conditionalso What are if statements used for?o How do you declare an if… else chain?o If() -> else if() -> elseo Logical OR (||) and Logical AND (&&) and Logical NOT (!=)

If statements are one of the most used and important functions in programming. They are essentially found anywhere.

33

Page 34: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

All it is really is... if this is true then do this. Else if this is true then do this instead. If the if statement or all of the previous conditions for the else if statements are not true then it will run the last statement the else statement.

o if() -> elseif() -> elseo Please note that the else statement case doesn’t have a condition to

check as it’s anything else left out by the conditions.

To check if something is equal to something use: ==

If you want either or of the conditions to be true for a true output use: || in between both of the conditions

o condition1 || condition 2

If you want both of the conditions to be true for a true output use: && in between both of the conditions

o condition1 && condition2

If you want the condition to be false for a true output use: != o condition1 != statement

Exercise: Make a program using the chain of if()... elseif()... and else. Ask the user to input their

GPA (use floats) and if they have done their programming homework (use y/n).

If the person has a GPA >= 3.0 and they have done their programming homework, then the output is: “You have become one with the force.”

If the person has a GPA >= 3.0 or they have done their programming homework, then the output is: “You need more training.”

34

Page 35: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

If the person has not done either, then the output is: “You have not become one with the force.”

Solution:#include <stdio.h>

int main() { float GPA; char prog_hw;

printf("What is your GPA?\n"); scanf(" %f", &GPA);

printf("Did you do your programming homework? (y/n) \n"); scanf(" %c", &prog_hw);

if(GPA >= 3.0 && prog_hw == 'y') { printf("You have become one with the force\n"); }

else if(GPA >= 3.0 || prog_hw == 'y') { printf("You need a little bit more training.\n"); }

else { printf("You have not become one with the force."); }

return 0;}

Conditionals (also switch) o What are switch statements?o Declaration of switch statementso Characters o Numberso Can you use switch for strings?o Importance of break;o Fall through in absence of break

35

Page 36: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Switch statements are most useful when you have to compare a variable/value to multiple different values and have to do something different for each of those values.

o They only work for integral or enumerated types i.e. characters or integer valueso They cannot work for strings and floats

Switch statements are declared like this:

switch(variable/value) {

case value1: code1; break;

case value2: code2; break; default: code3;}

The break statement tells the switch where to stop running the code, in the absence of a break statement it will “fall through” and do the code for the next cases until it encounters. In the example above if the variable/value matched up to value1 it would start running the code1 but stop right after encountering the break statement. If that statement was absent it would run code1 and code2 even though the variable/value doesn’t match up to value2 until it encountered the break and stop, this is call “falling through.” The default case is when the variable/value doesn’t match up to any of the cases.

Exercise:Ask the user to input their letter grade into a character variable. Then have a switch statement compare the value of the character variable with different cases. For a grade letter of A and B have one of them fall through to the next case such that it will output: “Excellent Work!” For a letter grade of C, output: “Try to study a little more.” For a letter grade of D and F, output: “Come to SI!” For the default case output: “Invalid Grade.”

36

Page 37: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Solution:#include <stdio.h> int main () { char grade = 'B'; printf("What is your letter grade?\n"); scanf(" %c", &grade);

switch(grade) { case 'A' : case 'B' : printf("Excellent Work!\n"); break; case 'C' : printf("Try to study a little more.\n" ); break; case 'D' : case 'F' : printf("Come to SI!\n" ); break; default : printf("Invalid grade.\n" ); } return 0;}

Data Structureso What are structures?o Members of a structureso Pointer to a structureo Dereferencing a structure

A structure is a data type created by the user which has the ability to consolidate many different types of variables all into one overarching data type.

37

Page 38: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

The programmer creates the many different types of variables into the overarching data type called members.

The declaration of a structure usually occurs before intmain () and follows:

struct [structure tag] {

member definition; member definition; ... member definition;} ;

Once you have defined the following before intmain(), you create variables just like int x or char c. In the following way struct [structure tag] my_var; my_var will now have all the members that you have defined previously. Those members can be accessed through a period like this => my_var.member

Advanced use of structs:o You can create a pointer that will point to the memory address of you new

variable struct and will be defined by struct [structure tag] * pvar = &my_var.

o To dereference the a pointers members it is through the following: pvar->member

Exercise: A start-up university called UCF is admitting a lot of new students. It wants the ability to store all of the new student data in a way that is easy and practical. Use Structures such that it will have a student’s name, ID #, GPA. Create a fictional students to see if your structures worked and output using the members of the newly created structure variable.

38

Page 39: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Solution:

#include <stdio.h>#include <string.h> struct student { char name[50]; int ID; float GPA;}; int main( ) {

struct student student1;

strcpy(student1.name, "Tuna Fish"); student1.ID = 12345; student1.GPA = 3.4;

printf("Student's Name: %s\n", student1.name); printf("Student's ID: %d\n", student1.ID); printf("Student's GPA: %f\n", student1.GPA);

// ADVANCED USERS (Using pointers to access members) struct student *pstudent1 = &student1;

printf("Student's Name: %s\n", pstudent1->name); printf("Student's ID: %d\n", pstudent1->ID); printf("Student's GPA: %f\n", pstudent1->GPA); return 0;}

File I/Oo What is File I/O?o What are the different modes of File I/O?o How do you open a file?o How do you read from a file?

39

Page 40: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o How do you write into a file?o How do you close a file?

File I/O stands for File Input/Output and is the process of creating, opening, reading and writing from text files and binary files.

In order to use File I/O you need to declare a file pointer. Which is declared in this format:

o FILE * nameofyourpointer; There are three major modes that can be used for functions such as fopen:

o r: opens a text file for readingo w: opens a text file for writingo a: opens a text file for appending

First you have to open a file, which you do by setting your pointer equal to the fopen(filename, mode) function.

To read from a file you can either use fgetc(file pointer) which reads characters or fgets(string dest, size n of characters to read, filepointer) which reads strings.

To write into a file you can either use fputc(int x, filepointer) to write a character or fputs(string, file pointer) which writes strings into a file.

To close a file, you use the fclose(file pointer) which helps to clear up memory for the computer.

ExerciseMake a text file hello.txt and ouput the string “hello world” into the text file. Then read from that text file and output the file contents.

#include <stdio.h>

int main(void) {

40

Page 41: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

FILE *fp; char buff[256];

fp = fopen("hello.txt", "w"); fputs("Hello World", fp); fclose(fp);

fp = fopen("hello.txt", "r"); fgets(buff, 256, fp);

printf("%s", buff); fclose(fp);

return 0;}

Bits and Byteso How do you print out a hexadecimal value? o How to turn decimal into Binary?o How to turn in binary into Decimal?o AND Operator (&)o OR Operator (|)

41

Page 42: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o XOR Operator (^)o NOT Operator (~)

In order to print out a hexademical value all one has to use is the format specifier %x instead of the format specifier that they would normally use for the datatype.

o Ex. int x = 43;o printf("Value of x: %x \n", x);

Output: Value of x: 2b

o

42

Page 43: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

43

Page 44: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

44

Page 45: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

45

Page 46: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

Dynamic Memory Allocationo What is the difference between dynamic and static memory allocation?o What header file should be included to use the functions for dynamic memory?o What are the different functions that can be used to dynamically allocate

memory?

There are two primary ways that a computer handles memory and programming languages allow you to tell the computer how to do it.

Static Memory Allocation: Memory is allocated exactly when the program is compiled. The problem with this type of memory is that it is “static.” It cannot change after the compiling of the code

Dynamic Memory Allocation: Memory is allocated as the program is running in real time. This allows for more flexibility for the programmer and allows to allocate memory depending on the user’s needs.

o The header file that should be defined is #include <stdlib.h>

There are four primary ways in which memory can be dynamically allocated within the computer

malloc(bytes): Allocates array with a specified amount of bytes realloc(address, additionalsize): Reallocates memory at a

specific address to one that has the same size and some additional size

calloc(elements, size): Allocates array with the specified number of elements in a specific size

free(address): Releases memory at a specified address

ExerciseCreate a character pointer called Pname. Then dynamically allocate enough memory for the pointer such that the size is big enough to hold a hundred characters. Check whether it was able

46

Page 47: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

to allocate the memory successfully and if it was, use the stringcopy function to store “Bruce” in that memory location and the print out that value.

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

int main() {

char * Pname;

Pname = malloc(100 * sizeof(char));

if (Pname == NULL) fprintf(stderr, "Was unable to allocate the memory\n"); else strcpy(Pname, "Bruce");

printf("%s", Pname);

return 0;}

Linked Listo What is a linked list?o How is a linked list declared?

47

Page 48: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o What is the purpose of a head node and a current node?o What are some header files that should be included before the start of the code?

A linked list is just a succession of data structures that are arranged in such a way that they are all “linked” together. They are linked by pointers and each pointer points to the memory location to the next data structure in the sequence. This is useful as it allows to expand and detract a structure whenever you it is necessary.

A linked list is declared with the following format: struct node {

char data;float value;struct node * next;};

The purpose of the head node is to denote the first node of the data structure sequence and the current node to denote the node that you are currently in.

Some header files that should be defined are stdio.h, string.h, stdlib.h, and stdbool.h. Please keep in mind that the ones you need to define depend on the program that you are trying to make.

Recursiono What is recursion?

48

Page 49: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

o Why is recursion useful?o When should recursion end?

Recursion is the process of a function calling on itself with the goal of redoing some set actions again. This is kind of like the concept of loop, but the function is usually exited by some condition that is dependent on what is being returned within the function. One must be careful not to create an infinite loop and one must clearly define when the function calls must stop.

Recursion is useful as sometimes it is impractical to use loops and instead it might be more useful to use recursion to repeat a certain set of actions until a certain goal is achieved.

ExerciseCreate a recursive function that takes a user inputted number from intmain() and returns the factorial of that number.

#include <stdio.h>int factorial(int num) {

if(num <=1) { return 1; } return num * factorial(num- 1);}int main() {

int user_input; int factorial_answer;

printf("What number do you want to take the factorial of?\n");

scanf("%d", &user_input);

factorial_answer = factorial(user_input);

printf("%d", factorial_answer);

return 0; }

References/Useful Linkshttps://www.programiz.com/c-programming/c-enumeration

49

Page 50: Table of Figures - ucfstudyunion.files.wordpress.com  · Web viewchar name[5] = “Alan”; OR... char name[]; Each string ends with a special character “\0” which is the null

https://ucfstudyunion.wordpress.com/computer-science/

https://www.hackerearth.com/practice/notes/why-a-header-file-such-as-includestdioh-is-used/https://www.tutorialspoint.com/cprogramming/index.htmhttps://www.tutorialspoint.com/c_standard_library/stdio_h.htmhttps://codeforwin.org/2015/05/list-of-all-format-specifiers-in-c-programming.htmlhttps://www.techbeamers.com/c-datatypes/http://durofy.com/ascii-values-table-generator-in-chttps://en.wikipedia.org/wiki/File:ASCII-Table.svghttp://howto-programminglanguages.blogspot.com/2011/10/c-escape-sequence-characters.htmlhttps://www.tutorialgateway.org/pass-array-to-functions-in-c/https://www.sitesbay.com/cprogramming/c-buffer-concepthttps://www.tutorialspoint.com/cprogramming/c_functions.htmhttp://www.c4learn.com/c-programming/c-dereferencing-pointer/https://www.tutorialspoint.com/cprogramming/c_arrays.htmhttps://www.tutorialspoint.com/cprogramming/c_for_loop.htmhttps://www.tutorialspoint.com/cprogramming/c_while_loop.htmhttps://www.tutorialspoint.com/cprogramming/c_do_while_loop.htmhttps://www.tutorialspoint.com/cprogramming/if_else_statement_in_c.htmhttps://www.tutorialspoint.com/cprogramming/switch_statement_in_c.htmhttps://www.tutorialspoint.com/cprogramming/c_structures.htm https://www.tutorialspoint.com/cprogramming/c_file_io.htmhttps://www.tutorialspoint.com/cprogramming/c_multi_dimensional_arrays.htmhttps://www.tutorialspoint.com/what-is-dynamic-memory-allocation-in-chttps://www.tutorialspoint.com/data_structures_algorithms/linked_list_program_in_c.htmhttps://www.tutorialspoint.com/cprogramming/c_recursion.htm

50