Input Output and Variables Ethan Cerami New York

Input, Output and Variables Ethan Cerami New York University 9/16/2020 Ethan Cerami, NYU 1

This Week n n Tuesday: n Basic Output: printf() n Introduction to Variables n Integer variables n Basic Input: scanf() Thursday: n Basic Arithmetic n Float variables n Operator Precedence n Promotion/Casting 9/16/2020 Ethan Cerami, NYU 2

Basic Output: printf () n n n printf () stands for “print formatted text. ” Prints any String of text directly to the computer screen. String: Any text appearing between quotes, e. g. “hello” 9/16/2020 Ethan Cerami, NYU 3

Sample Program /* Printing multiple lines with a single printf */ #include <stdio. h> main() { printf("Welcomenton. C!n"); /* Wait for user */ getchar(); } 9/16/2020 Ethan Cerami, NYU Note the n escape sequence creates a new line character. Welcome to C! 4

Escape Characters n n The character indicates an Escape sequence. Examples n t a \ " 9/16/2020 New Line Character Tab Character The AlarmBell Character Outputs a single Character Outputs a single " Character Ethan Cerami, NYU 5

Outputting a Quote Character n n n Quotes designate the beginning and end of a String. Hence, if you try to output a quote, the compiler gets confused. For example: printf ("He said, "Hello""); will result in a compilation error. To do it correctly, you must escape the “ character. For example: printf ("He said, “Hello""); 9/16/2020 Ethan Cerami, NYU 6

Variables n n Variable: a small piece or “chunk” of data. Variables enable one to temporarily store data within a program, and are therefore very useful. Note: variables are not persistent. When you exit your program, the data is deleted. To create persistent data, you must store it to a file system. 9/16/2020 Ethan Cerami, NYU 7

Data Types n n Every variable must have two things: a data type and a name. Data Type: defines the kind of data the variable can hold. n n 9/16/2020 For example, can this variable hold numbers? can it hold text? C supports several different data types. We are only going to look at one today. Ethan Cerami, NYU 8

C’s Three Main Data Types n n integers: the simplest data type in C. Used to hold whole numbers, e. g. 5, 25. floats: Used to hold fractional or decimal values, e. g. 3. 14, 10. 25. chars: Used to hold individual characters, e. g. “c”, “e” We will explore each one in detail in the next week. 9/16/2020 Ethan Cerami, NYU 9

Bucket Analogy n n It is useful to think of a variable as a bucket of data. The bucket has a unique name, and can only hold certain kinds of data. balance is a variable containing the value 200, and can contain only whole numbers. 200 balance 9/16/2020 Ethan Cerami, NYU 10

Variable Declaration n n Before you use a variable, you must declare it. (Not all languages require this, but C certainly does. ) Examples: /* Creates an integer variable */ int number; /* Creates a float variable */ float price; /* Creates a character variable */ char letter; 9/16/2020 Ethan Cerami, NYU 11

Example 1: Basic Arithmetic #include <stdio. h> Variable Declaration main () { int x, y, z; x = 5; y = 10; z = x + y; Data Type Variable Names Assignment Statements printf ("x: %dn", x); printf ("y: %dn", y); printf ("z: %dn", z); } 9/16/2020 Ethan Cerami, NYU 12

Assignment Statements n Assignments statements enable one to initialize variables or perform basic arithmetic. x = 5; y = 10; z = x + y; n Here, we simply initialize x and y and store their sum within the variable z. Note: If you forget to initialize your variables, the variable may contain any value. This is referred to as a garbage value. Hence, always initialize your variables! 9/16/2020 Ethan Cerami, NYU 13

Printing Variables n To print a variable, use the printf() statement: printf ("x: %dn", x); Format Specifier: Indicates the type of data to print. In this case, %d indicates whole digits or integer values. 9/16/2020 Name of variable to print. In this case, we print the variable x. Ethan Cerami, NYU 14

Rules for Naming Variables n § § § Variable Names: § Can contain letters, digits, or underscores _ § Cannot begin with a digit. Examples of Valid Variable names § int variable 1, variable_2; Examples of Invalid Variable names: § int 1 variable, variable#1 Remember, C is case sensitive, e. g. variable 1 VARIABLE 1 9/16/2020 Ethan Cerami, NYU 15

Basic Input: scanf() Input: any user supplied data. n Keyboard input, mouse input. n scanf (): read in keyboard input. n 9/16/2020 Ethan Cerami, NYU 16

Example 2: Using scanf() /* Addition program */ #include <stdio. h> #include <conio. h> main() { integer 1, integer 2, sum; printf("Enter first integern"); scanf("%d", &integer 1); printf("Enter second integern"); scanf("%d", &integer 2); sum = integer 1 + integer 2; printf("Sum is %dn", sum); /* declaration */ /* /* /* prompt */ read an integer */ assignment of sum */ print sum */ /* Wait for user to Any Key */ getch(); return 0; /* indicate that program ended successfully */ } 9/16/2020 Ethan Cerami, NYU 17

Quick Review /* Addition program */ #include <stdio. h> #include <conio. h> main() { integer 1, integer 2, sum; /* declaration */ printf("Enter first integern"); scanf("%d", &integer 1); printf("Enter second integern"); scanf("%d", &integer 2); sum = integer 1 + integer 2; printf("Sum is %dn", sum); /* /* /* 9/16/2020 Ethan Cerami, NYU prompt */ read an integer */ assignment of sum */ print sum */ 18

Quick Review: Comments /* Addition program */ Comments. Never underestimate the power of commenting! Your programs should always be well commented, and should include the following: n program description author of program date program was created 9/16/2020 Ethan Cerami, NYU n n 19

#include <conio. h> n n As mentioned last time, the #include statement includes another library so that you can reuse its functionality. conio. h: Console Input/Output n n 9/16/2020 Represents another library that deals specifically with keyboard input and output. Contains the getch() method which we will soon explore. Ethan Cerami, NYU 20

Quick Review: main () n n n You always need a main () function. Program execution will always begin at main(). Note, however, that the main() function can exist anywhere within your program, even at the very bottom. 9/16/2020 Ethan Cerami, NYU 21

Variable Declaration /* Addition program */ #include <stdio. h> #include <conio. h> main() { integer 1, integer 2, sum; /* declaration */ printf("Enter first integern"); scanf("%d", &integer 1); printf("Enter second integern"); scanf("%d", &integer 2); sum = integer 1 + integer 2; printf("Sum is %dn", sum); 9/16/2020 /* /* /* prompt */ read an integer */ assignment of sum */ print sum */ Ethan Cerami, NYU 22

Variable Declaration n Variable declaration: integer 1, integer 2, sum; This statements creates three variables, integer 1, integer 2, and sum. All are set to the integer data type. integer 1, integer 2, and sum can therefore only hold whole numbers. Note: Variable declaration must occur at the very top of your function. (you cannot stick it somewhere in the middle of your function!) 9/16/2020 Ethan Cerami, NYU 23

Basic Input: scanf () /* Addition program */ #include <stdio. h> #include <conio. h> main() { integer 1, integer 2, sum; /* declaration */ printf("Enter first integern"); /* prompt */ scanf("%d", &integer 1); /* read an integer */ printf("Enter second integern"); /* prompt */ scanf("%d", &integer 2); /* read an integer */ sum = integer 1 + integer 2; /* assignment of sum */ 9/16/2020 Ethan Cerami, NYU 24

Basic Input: scanf() n n If you want to read in data from the user, we use the scanf() function. scanf() reads in data from the keyboard, and stores it in a specific variable. Once stored in a variable, you can manipulate the data any way you want. Very useful for creating interactive applications which require input from the user. 9/16/2020 Ethan Cerami, NYU 25

scanf() Syntax n scanf has a very specific syntax, consisting of three parts: scanf("%d", &integer 1); Format specifier: indicates the kind of data to expect. In this case, %d stands for digits, e. g. whole numbers or integers. 9/16/2020 Note the & character. Without it, your computer may crash! (We will return to the exact meaning of the & character after the midterm. ) Ethan Cerami, NYU Indicates where to store the data. In this case, if the user types 5, the number 5 is stored in integer 1. 26

Two more tid-bits /* Addition program */ #include <stdio. h> #include <conio. h> main() { integer 1, integer 2, sum; printf("Enter first integern"); scanf("%d", &integer 1); printf("Enter second integern"); scanf("%d", &integer 2); sum = integer 1 + integer 2; printf("Sum is %dn", sum); } /* declaration */ /* /* /* prompt */ read an integer */ assignment of sum */ print sum */ /* Wait for user to Any Key */ getch(); return 0; /* indicate that program ended successfully */ 9/16/2020 Ethan Cerami, NYU 27

getch() Statement n getchar() n n n getch() n n n Contained in stdio. h Waits for the user to Press ENTER Contained in conio. h Waits for the user to Press any key Feel free to use either one. 9/16/2020 Ethan Cerami, NYU 28

Inter-Program Communication n n When you run your program in Windows, your program runs “on top” of Windows. For example: Hello World Program Windows Operating System 9/16/2020 Ethan Cerami, NYU 29

Communicating with Windows n n At the end of your program, you can tell Windows whether your program was successful or not. You communicate with windows via a return statement. Generally, return 0 indicates that everything ran just fine. -1 indicates that an error occurred. You will notice that all programs in the Text Book include a return statement. But, the programs in the packet may or may not (for this course, either option is fine, but some compilers may require a return statement. ) 9/16/2020 Ethan Cerami, NYU 30

Return 0 n return 0 indicates that your program ended successfully. Hello World Program “Hello Windows, everything ran just fine” Windows Operating System 9/16/2020 Ethan Cerami, NYU 31

Basic Mathematical Operators n + -Addition / Subtraction n * Multiplication n / n % Modulus Division 9/16/2020 Integer Division Ethan Cerami, NYU 32

Integer Division - The Problem n Suppose you have the following code: int x; x = 7 / 4; n n Using a calculator, the answer is 1. 75. But x can only hold integer values. 1. 75 is clearly not an integer value. 9/16/2020 Ethan Cerami, NYU 33

Integer Division - Solution n To understand the solution, you need to remember your 3 rd Grade Math (really. ) 1 4 7 4 The answer: 1 remainder 3 3 n n 7/4 = 1 (Integer Division) 7%4 = 3 (Modulus Division) 9/16/2020 Ethan Cerami, NYU 34

Example: Integer Division /* Integer and Modulus Division */ #include <stdio. h> 5/10: 0 5%10: 5 main () { int x = 5, y =10; printf ("5/10: %dn", x/y); printf ("5%%10: %dn", x%y); getchar(); } 9/16/2020 Ethan Cerami, NYU 35

Modulus Division (cont. ) n Second Example: 5/10 = 0 5%10 = 5 n 10 0 5 No matter what, you answers must be integers. 9/16/2020 Ethan Cerami, NYU 36

Operator Precedence n n Here’s another problem. What’s the answer to this? x = 7 + 3 * 6; Two Options (depending on the order of operations): n Perform addition first: 7 + 3 = 10 * 6 = 60 Perform multiplication first: 3*6 =18 7+18 = 25 Which option is correct? Clearly, we cannot have this kind of ambiguity. 9/16/2020 Ethan Cerami, NYU 37

Operator Precedence n n n Rules for evaluating mathematical expressions. Every programming language has similar rules. From left to right: n n n 9/16/2020 Parentheses are always evaluated first. Multiplication, division and modulus are evaluated next. Addition and subtraction are evaluated last. Ethan Cerami, NYU 38

Operator Precedence n Hence, option #2 is always correct: x = 7 + 3 * 6; Evaluates to x = 7 + 18 = 25 9/16/2020 Ethan Cerami, NYU 39

Float Data Types n n Float Data Type: Data type that can hold numbers with decimal values, e. g. 5. 14, 3. 14. Floats can be used to represent many values: n n n 9/16/2020 money long distances weight, etc. Ethan Cerami, NYU 40

Float Example (Program 2. 2) /* Float Example Program */ #include <stdio. h> main () { float var 1, var 2, var 3, sum; var 1 = 87. 25; var 2 = 92. 50; var 3 = 96. 75; %f: indicates floating values %. 2 f displays a floating point value with 2 decimal points. Output: Sum: 276. 50 sum = var 1 + var 2 + var 3; printf ("Sum: %. 2 f", sum); getchar(); } 9/16/2020 Ethan Cerami, NYU 41

Challenge: Find an Average n Suppose you want to determine a student’s average. int num = 4; float avg = 90+92+95+100/num; n Problem #1: Operator Precedence By rules of operator precedence, 100/4 is evaluated first. Hence, avg is set to: 302. n To solve this problem, use (): float avg = (90+92+95+100)/num; n 9/16/2020 Ethan Cerami, NYU 42

Finding an Average n Problem #2: n n 9/16/2020 90, 92, 95, 100 and 4 are all integers. Hence, this is integer division. Integer division can result in data truncation (or loss of data. ) Hence, avg is set to: 94, but the students real average is 94. 25. There actually three ways to solve this problem. Ethan Cerami, NYU 43

Rules of Promotion n n Promotion: when mixing ints and floats, everything is promoted to floats. In our average example, there are three ways to force promotion, and get the right answer of 94. 25: 1. change num to a float: float num = 4. 0; float avg = 90+92+95+100/num; 9/16/2020 Ethan Cerami, NYU 44

Rules of Promotion 2. Use a Cast Operator int num = 4; float avg = 90+92+95+100/(float)num; In this case, num is explicitly cast to a float. And, because we have one float, everything else is promoted. Note that you can also use the (int) cast to cast a float to an integer. 3. Divide by 4. 0 float avg = 90+92+95+100 / 4. 0; 9/16/2020 Ethan Cerami, NYU 45
- Slides: 45