45
Study Union: Spring 2020 Supplemental Instruction COP 3223C (Dr. Tovstolis) w/ Alan :) If you were able to come to the review session please fill out this quick survey for feedback so I can improve in the future! I worked very hard on this review! https://ucf.qualtrics.com/jfe/form/SV_ahMzuPHQwrHl5lj Topics that we will cover: Basic Introduction to Programming with C 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? Preprocessor Header o What are preprocessor Headers? #include <stdio.h> #include <stdlib.h> Int main(void)/int main() o What is it? o What is the primary purpose? o What should it return? Variables o Types of variables o Limits to variables o How variables are stored in the memory o Global variables 1

Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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

If you were able to come to the review session please fill out this quick survey for feedback so I can improve in the future! I worked very hard on this review! https://ucf.qualtrics.com/jfe/form/SV_ahMzuPHQwrHl5lj

Topics that we will cover:

Basic Introduction to Programming with Co 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?

Preprocessor Header o What are preprocessor Headers?

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

Int main(void)/int main()o What is it?o What is the primary purpose?o What should it return?

Variableso Types of variableso Limits to variableso How variables are stored in the memoryo Global variables

Format specifierso What do format specifiers do?o What are the different format specifiers depending on the type of variable?

Scanf() functiono What is the format of scanfo What does each argument mean in scanf

1

Page 2: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Printf()o How does it help you output something on the screen?o Arguments of printfo Special Characters

Functions o 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 are 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?

True/False?o What is considered true or false?

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

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

If… statements o What are if statements used for?o How do you declare an if… else chain?o If() -> else if() -> else

2

Page 3: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

o Logical OR (||) and Logical AND (&&) and Logical NOT (!=)

Switch Statementso 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

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

Bitwise Operatorso 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: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Table of Contents

Basic Introduction to Programming with C........................................................................................................................................6

Preprocessor Header..........................................................................................................................................................................7

Int main(void)/int main().....................................................................................................................................................................7

Variables............................................................................................................................................................................................. 8

Exercise:.........................................................................................................................................................................................9Solution:....................................................................................................................................................................................9

Format specifiers...............................................................................................................................................................................10

Scanf() function.................................................................................................................................................................................11

Printf()............................................................................................................................................................................................... 12

Exercise:.......................................................................................................................................................................................12Solution:..................................................................................................................................................................................13

Functions...........................................................................................................................................................................................14

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

Pointers............................................................................................................................................................................................. 17

Exercise:.......................................................................................................................................................................................18Solution:..................................................................................................................................................................................19

Arrays................................................................................................................................................................................................ 20

Exercise:.......................................................................................................................................................................................21Solution:..................................................................................................................................................................................22

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

True/False?.......................................................................................................................................................................................24

For Loops..........................................................................................................................................................................................24

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

While Loops.......................................................................................................................................................................................26

Exercise:.......................................................................................................................................................................................27Solution:..................................................................................................................................................................................28

If… else statements............................................................................................................................................................................28

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

Switch Statements..............................................................................................................................................................................30

Exercise:............................................................................................................................................................................................31Solution:..................................................................................................................................................................................32

4

Page 5: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Structures..........................................................................................................................................................................................32

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

Bitwise Operators..............................................................................................................................................................................34

........................................................................................................................................................................................................... 37

References/Useful Links....................................................................................................................................................................38

Table of FiguresFigure 1: Types of Variable with Ranges............................................................................................................................................8

Figure 2: ASCII - American Standard Code for Information Exchange.............................................................................................8

Figure 3: Format Specifiers...............................................................................................................................................................10

Figure 4: Special Characters..............................................................................................................................................................11

Figure 5: Array Pictorial Representation...........................................................................................................................................21

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

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

5

Page 6: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Basic Introduction to Programming with Co 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? 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?

The computers 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).

6

Page 7: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Preprocessor Header o What are preprocessor Headers?

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

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 where you put the #include. 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()

Int main(void)/int main()o What is it?o What is the primary purpose?o What should it return?

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.

7

Page 8: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Variableso Types of variableso Limits to variableso How variables are stored in the memoryo Global variables

8

Page 9: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Figure 2: ASCII - American Standard Code for Information Exchange

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’;

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

9

Figure 1: Types of Variable with Ranges

Page 10: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Solution:

#include <stdio.h>

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

printf("%d", name);

return 0;}

Format specifierso What do format specifiers do?o What are the different format specifiers depending on the type of variable?

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().

10

Page 11: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Figure 3: Format Specifiers

Scanf() functiono What is the format of scanf()o What does each argument mean in scanf()

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.

11

Page 12: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

Printf()o How does it help you output something on the screen?o Arguments of printfo Special Characters

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.

Figure 4: Special Characters

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

int main() {

char favorite_letter;

12

Page 13: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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.

Fixed Code:#include <stdio.h>

int main() {

char favorite_letter;char second_favorite_letter;

13

Page 14: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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.

Functions o 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?

14

Page 15: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

o What are 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 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>

15

Page 16: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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);

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() {

16

Page 17: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

int vanll_ice_creams;int choc_ice_creams;

...return 0;}

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

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.

17

Page 18: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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

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;

18

Page 19: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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);

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;

19

Page 20: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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);

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];

20

Page 21: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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);

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>

21

Figure 5: Array Pictorial Representation

Page 22: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

int main() {

char name[99];

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

return 0;}

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};

22

Page 23: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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;}

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);

23

Page 24: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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

return 0;}

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

True/False?o What is considered true or false?

In programming with C anything that consist of the following or the like is considered False:

1. NULL 2. Boolean type is equal to false 3. 0

Anything that doesn’t belong to this type is true Any set of string values Any decimal value Any set of character values

For Loopso How do you declare a for loop?

24

Page 25: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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.

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>

25

Page 26: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

int main() { int z;

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

return 0;}

While Loopso How do you declare a while

loop?o What is a while loop used for?

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.

26

Page 27: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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.

Solution:#include <stdio.h>

int main() {

27

Figure 7: While Loop Pictorial Representation

Page 28: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

int z = 64;

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

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!

If… else statements 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 (!=)

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

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.

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

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

28

Page 29: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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

condition1 || condition 2

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

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

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.”

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

Solution:#include <stdio.h>

29

Page 30: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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 == 'n') { printf("You need a little bit more training.\n"); }

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

return 0;}

Switch Statementso 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

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) {

30

Page 31: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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.”

Solution:#include <stdio.h> int main () {

31

Page 32: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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;}

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.

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;

32

Page 33: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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.

Solution:

#include <stdio.h>#include <string.h> struct student { char name[50]; int ID;

33

Page 34: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

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;}

Bitwise Operatorso 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 (~)

34

Page 35: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

35

Page 36: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

36

Page 37: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

37

Page 38: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

38

Page 39: Basic Introduction to Programming with C€¦ · Web viewarray[0] would hold the value 5 & array[3] would hold the value 4. The dirty truth about arrays is that they are actually

References/Useful Linkshttps://www.programiz.com/c-programming/c-enumerationhttps://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

39