Title: Input, Output and Variables
1Input, Output and Variables
- Ethan Cerami
- New York University
2This Week
- Tuesday
- Basic Output printf()
- Introduction to Variables
- Integer variables
- Basic Input scanf()
- Thursday
- Basic Arithmetic
- Float variables
- Operator Precedence
- Promotion/Casting
3Basic Output printf ()
- 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
4Sample Program
- / Printing multiple lines
- with a single printf /
- include ltstdio.hgt
-
- main()
-
- printf("Welcome\nto\nC!\n")
-
- / Wait for user /
- getchar()
-
Note the \n escape sequence creates a new line
character.
Welcome to C!
5Escape Characters
- The \ character indicates an Escape sequence.
- Examples
- \n New Line Character
- \t Tab Character
- \a The Alarm\Bell Character
- \\ Outputs a single \ Character
- \" Outputs a single " Character
6Outputting a Quote Character
- 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\"")
7Variables
- 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.
8Data Types
- Every variable must have two things a data type
and a name. - Data Type defines the kind of data the
variable can hold. - 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.
9Cs Three Main Data Types
- 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.
10Bucket Analogy
- 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
11Variable Declaration
- 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
12Example 1 Basic Arithmetic
include ltstdio.hgt main () int x, y, z x
5 y 10 z x y printf ("x d\n",
x) printf ("y d\n", y) printf ("z d\n",
z)
Variable Declaration
Variable Names
Data Type
Assignment Statements
13Assignment Statements
- Assignments statements enable one to initialize
variables or perform basic arithmetic. - x 5
- y 10
- z x y
- 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!
14Printing Variables
- To print a variable, use the printf() statement
-
- printf ("x d\n", x)
-
Format Specifier Indicates the type of data to
print. In this case, d indicates whole digits
or integer values.
Name of variable to print. In this case, we
print the variable x.
15Rules for Naming Variables
- Variable Names
- Can contain letters, digits, or underscores _
- Cannot begin with a digit.
- Examples of Valid Variable names
- int variable1, variable_2
- Examples of Invalid Variable names
- int 1variable, variable1
- Remember, C is case sensitive, e.g. variable1 ?
VARIABLE1
16Basic Input scanf()
- Input any user supplied data.
- Keyboard input, mouse input.
- scanf () read in keyboard input.
17Example 2 Using scanf()
- / Addition program /
- include ltstdio.hgt
- include ltconio.hgt
- main()
-
- int integer1, integer2, sum /
declaration / - printf("Enter first integer\n") / prompt /
- scanf("d", integer1) / read an
integer / - printf("Enter second integer\n") / prompt /
- scanf("d", integer2) / read an
integer / - sum integer1 integer2 /
assignment of sum / - printf("Sum is d\n", sum) / print sum
/ - / Wait for user to Any Key /
- getch()
- return 0 / indicate that program ended
successfully /
18Quick Review
/ Addition program / include
ltstdio.hgt include ltconio.hgt main()
-
- int integer1, integer2, sum /
declaration / - printf("Enter first integer\n") / prompt /
- scanf("d", integer1) / read an
integer / - printf("Enter second integer\n") / prompt /
- scanf("d", integer2) / read an
integer / - sum integer1 integer2 /
assignment of sum / - printf("Sum is d\n", sum) / print sum
/ -
19Quick Review Comments
- / Addition program /
- Comments. Never underestimate the power of
commenting! - Your programs should always be well commented,
and should include the following - program description
- author of program
- date program was created
20include ltconio.hgt
- As mentioned last time, the include statement
includes another library so that you can reuse
its functionality. - conio.h Console Input/Output
- Represents another library that deals
specifically with keyboard input and output. - Contains the getch() method which we will soon
explore.
21Quick Review main ()
- 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.
22Variable Declaration
- / Addition program /
- include ltstdio.hgt
- include ltconio.hgt
- main()
-
-
- printf("Enter first integer\n") / prompt /
- scanf("d", integer1) / read an
integer / - printf("Enter second integer\n") / prompt /
- scanf("d", integer2) / read an
integer / - sum integer1 integer2 /
assignment of sum / - printf("Sum is d\n", sum) / print sum
/ -
int integer1, integer2, sum / declaration
/
23Variable Declaration
- Variable declaration
- int integer1, integer2, sum
- This statements creates three variables,
integer1, integer2, and sum. All are set to the
integer data type. - integer1, integer2, 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!)
24Basic Input scanf ()
- / Addition program /
- include ltstdio.hgt
- include ltconio.hgt
- main()
-
- int integer1, integer2, sum /
declaration / - printf("Enter second integer\n") / prompt /
- scanf("d", integer2) / read an
integer / - sum integer1 integer2 /
assignment of sum / -
printf("Enter first integer\n") / prompt
/ scanf("d", integer1) / read an
integer /
25Basic Input scanf()
- 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.
26scanf() Syntax
- scanf has a very specific syntax, consisting of
three parts - scanf("d", integer1)
Format specifier indicates the kind of data to
expect. In this case, d stands for digits, e.g.
whole numbers or integers.
Note the character. Without it, your computer
may crash! (We will return to the exact meaning
of the character after the midterm.)
Indicates where to store the data. In this case,
if the user types 5, the number 5 is stored in
integer1.
27Two more tid-bits
- / Addition program /
- include ltstdio.hgt
- include ltconio.hgt
- main()
-
- int integer1, integer2, sum /
declaration / - printf("Enter first integer\n") / prompt /
- scanf("d", integer1) / read an
integer / - printf("Enter second integer\n") / prompt /
- scanf("d", integer2) / read an
integer / - sum integer1 integer2 /
assignment of sum / - printf("Sum is d\n", sum) / print sum
/ -
/ Wait for user to Any Key / getch()
return 0 / indicate that program ended
successfully /
28getch() Statement
- getchar()
- Contained in stdio.h
- Waits for the user to Press ENTER
- getch()
- Contained in conio.h
- Waits for the user to Press any key
- Feel free to use either one.
29Inter-Program Communication
- When you run your program in Windows, your
program runs on top of Windows. - For example
Hello World Program
Windows Operating System
30Communicating with Windows
- 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.)
31Return 0
- return 0 indicates that your program ended
successfully.
Hello World Program
Hello Windows, everything ran just fine
Windows Operating System
32Basic Mathematical Operators
- - Addition / Subtraction
- Multiplication
- / Integer Division
- Modulus Division
33Integer Division - The Problem
- Suppose you have the following code
- Using a calculator, the answer is 1.75.
- But x can only hold integer values. 1.75 is
clearly not an integer value.
int x x 7 / 4
34Integer Division - Solution
- To understand the solution, you need to remember
your 3rd Grade Math (really.) - 7/4 1 (Integer Division)
- 74 3 (Modulus Division)
1
The answer 1 remainder 3
4
7
4
3
35Example Integer Division
- / Integer and Modulus Division /
- include ltstdio.hgt
- main ()
- int x 5, y 10
- printf ("5/10 d\n", x/y)
- printf ("510 d\n", xy)
- getchar()
5/10 0 510 5
36Modulus Division (cont.)
- Second Example
- No matter what, you answers must be integers.
0
5/10 0 510 5
5
10
0
5
37Operator Precedence
- Heres another problem. Whats the answer to
this? - x 7 3 6
- Two Options (depending on the order of
operations) - Perform addition first 7 3 10 ? 10 6
60 - Perform multiplication first 36 18 ? 718
25 - Which option is correct? Clearly, we cannot have
this kind of ambiguity.
38Operator Precedence
- Rules for evaluating mathematical expressions.
- Every programming language has similar rules.
- From left to right
- Parentheses are always evaluated first.
- Multiplication, division and modulus are
evaluated next. - Addition and subtraction are evaluated last.
39Operator Precedence
- Hence, option 2 is always correct
x 7 3 6 Evaluates to x 7 18 25
40Float Data Types
- 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
- money
- long distances
- weight, etc.
41Float Example (Program 2.2)
- / Float Example Program /
- include ltstdio.hgt
- main ()
-
- float var1, var2, var3, sum
- var1 87.25
- var2 92.50
- var3 96.75
- sum var1 var2 var3
- printf ("Sum .2f", sum)
- getchar()
- f indicates floating values
- .2f displays a floating point value with 2
decimal points. - Output
- Sum 276.50
42Challenge Find an Average
- Suppose you want to determine a students
average. - int num 4
- float avg 909295100/num
- Problem 1 Operator Precedence
- By rules of operator precedence, 100/4 is
evaluated first. Hence, avg is set to 302. - To solve this problem, use ()
- float avg (909295100)/num
43Finding an Average
- Problem 2
- 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 are actually three ways to solve this
problem.
44Rules of Promotion
- 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 909295100/num
45Rules of Promotion
- 2. Use a Cast Operator
- int num 4
- float avg 909295100/(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 909295100 / 4.0