Input, Output and Variables - PowerPoint PPT Presentation

About This Presentation
Title:

Input, Output and Variables

Description:

Input, Output and Variables – PowerPoint PPT presentation

Number of Views:752
Avg rating:3.0/5.0
Slides: 46
Provided by: Cer8
Category:

less

Transcript and Presenter's Notes

Title: Input, Output and Variables


1
Input, Output and Variables
  • Ethan Cerami
  • New York University

2
This Week
  • Tuesday
  • Basic Output printf()
  • Introduction to Variables
  • Integer variables
  • Basic Input scanf()
  • Thursday
  • Basic Arithmetic
  • Float variables
  • Operator Precedence
  • Promotion/Casting

3
Basic 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

4
Sample 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!
5
Escape 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

6
Outputting 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\"")

7
Variables
  • 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.
8
Data 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.

9
Cs 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.

10
Bucket 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
11
Variable 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

12
Example 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
13
Assignment 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!

14
Printing 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.
15
Rules 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

16
Basic Input scanf()
  • Input any user supplied data.
  • Keyboard input, mouse input.
  • scanf () read in keyboard input.

17
Example 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 /

18
Quick 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
    /

19
Quick 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

20
include 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.

21
Quick 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.

22
Variable 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
/
23
Variable 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!)
24
Basic 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 /
25
Basic 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.

26
scanf() 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.
27
Two 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 /
28
getch() 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.

29
Inter-Program Communication
  • When you run your program in Windows, your
    program runs on top of Windows.
  • For example

Hello World Program
Windows Operating System
30
Communicating 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.)

31
Return 0
  • return 0 indicates that your program ended
    successfully.

Hello World Program
Hello Windows, everything ran just fine
Windows Operating System
32
Basic Mathematical Operators
  • - Addition / Subtraction
  • Multiplication
  • / Integer Division
  • Modulus Division

33
Integer 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
34
Integer 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
35
Example 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
36
Modulus Division (cont.)
  • Second Example
  • No matter what, you answers must be integers.

0
5/10 0 510 5
5
10
0
5
37
Operator 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.

38
Operator 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.

39
Operator Precedence
  • Hence, option 2 is always correct

x 7 3 6 Evaluates to x 7 18 25
40
Float 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.

41
Float 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

42
Challenge 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

43
Finding 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.

44
Rules 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

45
Rules 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
Write a Comment
User Comments (0)
About PowerShow.com