Conditions and Boolean Expressions

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
CPS120: Introduction to Computer Science Lecture 8.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
CPS120: Introduction to Computer Science
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Math operations 9/19/16.
UMBC CMSC 104 – Section 01, Fall 2016
Java Coding – part 2 David Davenport Computer Eng. Dept.,
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Chapter 2 - Introduction to C Programming
Tokens in C Keywords Identifiers Constants
EGR 2261 Unit 4 Control Structures I: Selection
Debugging and Random Numbers
ICS103 Programming in C Lecture 3: Introduction to C (2)
Multiple variables can be created in one declaration
Variables and Primative Types
Assignment and Arithmetic expressions
Variables, Expressions, and IO
Intro to C Tutorial 4: Arithmetic and Logical expressions
Other Kinds of Arrays Chapter 11
Chapter 2 - Introduction to C Programming
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Arrays Arrays are data structures that allow us to store data of the same type in contiguous memory locations. That was a pretty dense statement!
Introduction to C Programming
Math in C The math blocks you've used in Scratch can all be recreated in C!
Loops The loop blocks you've used in Scratch can all be recreated in C! Loops allow for the repetition of code until a condition is met. There are three.
Arrays, For loop While loop Do while loop
Building Java Programs Chapter 2
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
CS1100 Computational Engineering
Introduction to Java, and DrJava part 1
Chapter 2 - Introduction to C Programming
Arithmetic Expressions & Data Conversions
Introduction to C Programming
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.
Conditions and Boolean Expressions
Lectures on Numerical Methods
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Chapter 4 Selection.
Chapter 2 - Introduction to C Programming
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Introduction to Java, and DrJava
Expressions and Assignment
SSEA Computer Science: Track A
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Introduction to Primitives
Introduction to Primitives
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
Chapter 2 - Introduction to C Programming
Primitive Types and Expressions
Introduction to Java, and DrJava part 1
EECE.2160 ECE Application Programming
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Introduction to C Programming
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Arithmetic Expressions & Data Conversions
Presentation transcript:

Conditions and Boolean Expressions The conditionals and boolean expression blocks you've used in Scratch can all be recreated in C!

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!

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.

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.

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.

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.

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?

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

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?

Math in C The math blocks you've used in Scratch can all be recreated in C!

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.

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.

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.

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

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.

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

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

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

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 0.10000000149011611938 will print rather than simply 0.10000000000000000000? 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!

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

We are used to decimal notation: 1 6 3 102 101 100 1*102 + 6*101 + 3*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.

Computers store and process data via binary notation: 1 0 1 0 0 0 1 1 27 26 25 24 23 22 21 20 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.

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.

Addition and Subtraction (Don’t forget to carry your 1s) 1 1 10 010 0 - 0 0 0 1 0 1 1 0 1 0 1 0 1 01 11 1 + 0 1 0 0 0 1 1 1 1 1 0 0 Addition and subtraction in binary works the same way as in decimal. Start on the right, and carry the 1s as needed.

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!

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 65 87 30 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.

Accessing Array Elements 1 2 65 87 30 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.

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

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?

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

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.