0) printf("You picked a positive number!\n"); } Conditions are important as they allow us to introduce logic into our programs. Note how the code within this if block will only execute if the condition n > 0 evaluates to true. Conditions of if blocks are always boolean expressions that evaluate to either true or false. We’ll dive into boolean conditions in more detail on the next slide!"> 0) printf("You picked a positive number!\n"); } Conditions are important as they allow us to introduce logic into our programs. Note how the code within this if block will only execute if the condition n > 0 evaluates to true. Conditions of if blocks are always boolean expressions that evaluate to either true or false. We’ll dive into boolean conditions in more detail on the next slide!">
Download presentation
Presentation is loading. Please wait.
1
Conditions and Boolean Expressions
The conditionals and boolean expression blocks you've used in Scratch can all be recreated in C!
2
If #include <cs50.h> #include <stdio.h> int main(void) {
printf("Give me an integer: "); int n = GetInt(); if (n > 0) printf("You picked a positive number!\n"); } Conditions are important as they allow us to introduce logic into our programs. Note how the code within this if block will only execute if the condition n > 0 evaluates to true. Conditions of if blocks are always boolean expressions that evaluate to either true or false. We’ll dive into boolean conditions in more detail on the next slide!
3
Boolean Expressions <= > Evaluates to either true or false.
>= == != ! Boolean expressions like the ones on the left can only evaluate to boolean values of true or false. You can use them to compare values, e.g. 4 < 3 evaluates to false and 4 <= 3 evaluates to true. Note that == is used to compare two numbers for equality. ! means "not", and negates the values of a boolean expression. So !(4 < 3) evaluates to true. Additionally, in C, anything with a value of zero (e.g. int i = 0) evaluates to false, and any other value evaluates to true.
4
Combining Boolean Expressions
Logical OR: || if (x < 0 || x > 100) { printf("invalid\n"); } Logical AND: && if (x >= 0 && x <= 100) { printf("valid\n"); } You can combine boolean expressions using the logical AND (&&) and OR (||) operators. Here, invalid will print if the value of x is less than 0 or greater than 100, and valid will print if the value of x is between 0 and 100, inclusive.
5
If... Else int main(void) { printf("Give me an integer: ");
int n = GetInt(); if (n > 0) printf("You picked a positive number!\n"); } else printf("You picked a negative number!\n"); We’ve seen that an if block can stand alone. It can also be paired with else. If n > 0 does not evaluate to be true, the code within else will execute. The important thing to remember is that the code within the if and else blocks are exclusive of each other: the else block will never execute if the if block already did! This may seem trivial for now, but you'll soon see how this logic can get a bit confusing. But anyway, back to the code! 0 is not a negative number, so this program is flawed. We’ll fix it on the next slide.
6
If... Else if... Else int main(void) { int n = GetInt(); if (n > 0)
printf("You picked a positive number!\n"); } else if (n < 0) printf("You picked a negative number!\n"); else printf("You picked 0!\n"); The if... else construct can be extended to include three or more code blocks as in this slide's example. Again, there's no way that more than one of those three printf statements can possibly execute, because once a condition is found to be true and its associated code executes, none of the other conditions will even be evaluated.
7
printf("Enter your grade: "); int n = GetInt(); if (n > 90)
int main(void) { printf("Enter your grade: "); int n = GetInt(); if (n > 90) printf("You got an A!\n"); } if (n > 80) printf("You got a B!\n"); if (n > 70) printf("You got a C!\n"); In contrast, multiple if blocks are not necessarily exclusive. What will print if I enter the number 95? Why? How can we fix this bug?
8
Switch Statements int main(void) {
printf("Give me an integer between 1 and 3: "); int n = GetInt(); switch (n) case 1: printf("You picked a low number.\n"); break; case 2: printf("You picked a medium number.\n"); case 3: printf("You picked a high number.\n"); default: printf("Invalid.\n"); } This syntax is called a switch statement. A switch statement takes a variable (n in this case) and determines which case statement will execute based on the value of that variable. Finally, default defines behavior when no other case statement is executed. ** Note that switch statements can also be used on characters instead of integers. **
9
Ternary Operator #include <cs50.h> #include <stdio.h>
int main(void) { printf("Give me an integer: "); int n = GetInt(); string s = (n > 100) ? "high" : "low"; printf("You picked a %s number!\n", s); } The ternary operator ?: is another kind of conditional. Here's how it works: If n > 100 is true, the value to the left of the colon "high" is assigned to s. If n > 100 is false, the value to the right of the colon "low" is assigned to s. So what will print out if the user inputs a value of 55?
10
Math in C The math blocks you've used in Scratch can all be recreated in C!
11
Numerical Variables int float double long long
Numerical data in C is classified into several different types. From a variable’s type, you’ll be able to tell what kind of data it can store, how much data it can store, and which operations can be performed on this data. An int is a whole number. The appliance uses 32 bits to store an int. A float is a number with a decimal point. The appliance uses 32 bits to store a float. A double is a number with a decimal point, but with more space for precision after the decimal point. The appliance uses 64 bits to store a double. A long long is a whole number that is twice as big in memory as an int. The appliance uses 64 bits to store a long long.
12
Let’s add some ints! // declare x int x; // initialize x x = 2;
// declare and initialize y int y = x + 1; Here, we sum two variables of type int. Let's think very carefully about what's happening as these three lines of code execute: The first line declares an int named x. More precisely, it asks the operating system for enough memory to store an int and gives that chunk of memory the name x. The second line initializes x by assigning it a value of 2. Remember that in C, a single equal sign is called an assignment operator. Whatever's to the right of the equal sign will be stored in the variable to the left of the equal sign. The third line declares and initializes an int named y in a single line of code.
13
Division int main(void) { // declare and initialize answer
float answer = 1 / 10; // print answer to two decimal places printf("%.2f\n", answer); } Let’s try some division next, and store the result of our division in a float because we know it will be a decimal value. %.2f tells the OS to print a floating-point number, but only to two decimal places. What will print? 0.00 Why? 1 and 10 are ints. In C, an int divided by an int is an int and any decimal places will be truncated off.
14
Fixed version: Typecasting
int main(void) { // declare and initialize answer float answer = (float) 1 / (float) 10; // print answer to two decimal places printf("%.2f\n", answer); } We can fix this! We can use this syntax (desired data type within parentheses) to cast the ints 1 and 10 to floats. This is called typecasting. A float divided by a float is a float, which preserves decimal places! What will print this time? 0.10
15
Another way int main(void) { // declare and initialize answer
float answer = 1.0 / 10.0; // print answer to two decimal places printf("%.2f\n", answer); } Another way to accomplish the same thing is to replace the ints 1 and 10 with floats 1.0 and 10.0. This method also results in the printing of 0.10.
16
Operator Precedence What is x? 1. int x = 2 * 10 + 10 / 2 + 2;
Remember "order of operations" from elementary school? The same concept applies in programming and is called operator precedence. 1. 27 2. 22 3. 10
17
Modulo 1. 55 % 10 2. 3 % 5 3. 8 % 8 4. 16 % 15 The modulo operator gives you the remainder of the division of the first number by the second. 1. 5 2. 3 3. 0 4. 1
18
What will print? int main(void) { // declare and initialize x, y, z
int x = 1; int y = 2; int z = (x + y) * y % y + y; // print z printf("%i\n", z); } What will be printed out? 2
19
Floating Point Imprecision
int main(void) { // initialize x and y float answer = 1.0 / 10.0; // print answer to two decimal places printf("%.20f\n", answer); } Why is it that will print rather than simply ? Some fractions like 0.1 can't be represented precisely using a finite number of binary bits. This is known as floating point imprecision and can cause significant rounding errors if you're not careful!
20
Everything that goes on under the hood of a computer is done in binary -- the language of 0s and 1s.
If we have only two numbers, it's very easy to represent them in the physical world using electricity. You can think of each binary digit as a switch or a light bulb that can be either on or off, where by convention 0 is thought of as "off" and 1 is "on".
21
We are used to decimal notation:
1* * *100 = 163 Let's think more carefully about decimal notation. To represent the number 163, we've got a 3 in the 1s place (100), a 6 in the 10s place (101), and a 1 in the 100s place (102). You get 163 when you multiply these digits by their respective powers of 10 and sum them.
22
Computers store and process data via binary notation:
1*27 + 0*26 + 1*25 + 0*24 + 0*23 + 0*22 + 1*21 + 1*20 = 163 To represent this same number in binary, you'll need a 1 in the 1s place (20), a 1 in the 2s place (21), a 1 in the 32s place (25), and a 1 in the 128s place (27). You get 163 when you multiply these digits by their respective powers of 2 and sum them.
23
Converting Binary to Decimal (and vice versa)
1 = 1*20 = 1 10 = 1*21 + 0*20 = 2 11 = 1*21 + 1*20 = 3 100 = 1*22 + 0*21 + 0*20 = 4 101 = 1*22 + 0*21 + 1*20 = 5 Let's count to 5 in binary! Note how we can multiply the binary digits by their respective powers of two and sum them to convert to a decimal value.
24
Addition and Subtraction (Don’t forget to carry your 1s)
Addition and subtraction in binary works the same way as in decimal. Start on the right, and carry the 1s as needed.
25
Arrays 1 2 3 4 5 Arrays are data structures that allow us to store data of the same type in contiguous memory locations. That was a pretty dense statement! To better understand the concept of an array, think back to the last time you picked up mail in the Science Center basement or your house's mailroom. An array is simply a block of contiguous space in memory (the mail center) that has been partitioned into identically-sized chunks (mailboxes). Each chunk can store a certain amount of data (mail) that can be accessed by an index number (mailbox number). Note that array indices in C always start at 0!
26
65 87 30 Creating an Array 1 2 <data type> name[<size>];
Example: int temperature[3]; temperature[0] = 65; temperature[1] = 87; temperature[2] = 30; OR int temperature[] = { 65, 87, 30 }; 1 2 Declare an array by specifying the data type it will store, its name, as well as its size. Here, we declare an array of 3 ints called temperature and load it with values. Alternatively, you can declare and initialize the array in a single step (in which case stating the size is optional). Because arrays store data contiguously in memory, array size is fixed after array declaration. You are effectively asking the OS to reserve the appropriate number of contiguous chunks of memory for the array's elements. There's no guarantee that more memory adjacent to your array will be available for use later, so arrays cannot easily grow.
27
Accessing Array Elements
1 2 for (int i = 0; i < 3; i++) { printf("%d\n", temperature[i]); } Because each element is associated with an array index, we have random access to all of the elements in an array. In other words, we can access any element in a single step by indexing into the array. This is a big deal because algorithms like binary search depend on random access. This code prints out all elements of the temperature array.
28
#include <stdio.h> #include <cs50.h> #define CLASS_SIZE 30
int main(void) { // declare array int scores_array[CLASS_SIZE]; // populate array for (int i = 0; i < CLASS_SIZE; i++) printf("Enter score for student %d: ", i); scores_array[i] = GetInt(); } } Here's an example of the usage of an array to keep track of student scores. This code prompts the user to enter a score for each student. Scores are stored in scores_array.
29
Where's the bug? string class[3] = { "Sam", "Jess", "Kim" };
for (int i = 0; i <= 3; i++) { printf("%s\n", class[i]); } What's the index number of the last element in an array of size n?
30
Multidimensional Arrays
0,0 0,1 0,2 x x 1,0 1,1 1,2 char board[3][3]; board[1][1] = 'o'; board[0][0] = 'x'; board[2][0] = 'o'; board[0][2] = 'x'; o Arrays can be multidimensional. You can think of multidimensional arrays as "arrays of arrays." Here, we declare and initialize a 2-dimensional array tic-tac-toe board. Note that dimensions must be declared explicitly for multidimensional arrays! 2,0 2,1 2,2 o
31
Accessing Multidimensional Array Elements
// print out all elements for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) printf("%c", board[i][j]); printf("\n"); } This code uses nested for loops to print out all elements of the tic-tac-toe board array.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.