Input, Output and Variables
Download
Report
Transcript Input, Output and Variables
Input, Output
and Variables
Ethan Cerami
New York University
7/21/2015
Ethan Cerami, NYU
1
This Week
Tuesday:
Basic Output: printf()
Introduction to Variables
Integer variables
Basic Input: scanf()
Thursday:
Basic Arithmetic
Float variables
Operator Precedence
Promotion/Casting
7/21/2015
Ethan Cerami, NYU
2
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”
7/21/2015
Ethan Cerami, NYU
3
Sample Program
/* Printing multiple lines
with a single printf */
#include <stdio.h>
main()
{
printf("Welcome\nto\nC!\n");
/* Wait for user */
getchar();
}
7/21/2015
Ethan Cerami, NYU
Note the \n escape
sequence creates a
new line character.
Welcome
to
C!
4
Escape Characters
The \ character indicates an Escape
sequence.
Examples
\n
\t
\a
\\
\"
7/21/2015
New Line Character
Tab Character
The Alarm\Bell Character
Outputs a single \ Character
Outputs a single " Character
Ethan Cerami, NYU
5
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/21/2015
Ethan Cerami, NYU
6
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.
7/21/2015
Ethan Cerami, NYU
7
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.
7/21/2015
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
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.
7/21/2015
Ethan Cerami, NYU
9
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
7/21/2015
Ethan Cerami, NYU
10
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;
7/21/2015
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;
printf ("x:
printf ("y:
printf ("z:
Data Type
Variable Names
Assignment Statements
%d\n", x);
%d\n", y);
%d\n", z);
}
7/21/2015
Ethan Cerami, NYU
12
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!
7/21/2015
Ethan Cerami, NYU
13
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.
7/21/2015
Name of variable to
print. In this case, we
print the variable x.
Ethan Cerami, NYU
14
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, variable#1
Remember, C is case sensitive, e.g. variable1
VARIABLE1
7/21/2015
Ethan Cerami, NYU
15
Basic Input: scanf()
Input: any user supplied data.
Keyboard input, mouse input.
scanf (): read in keyboard input.
7/21/2015
Ethan Cerami, NYU
16
Example 2: Using scanf()
/* Addition program */
#include <stdio.h>
#include <conio.h>
main()
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d\n", sum);
/* declaration */
/*
/*
/*
/*
/*
/*
prompt */
read an integer */
prompt */
read an integer */
assignment of sum */
print sum */
/* Wait for user to Any Key */
getch();
return 0; /* indicate that program ended successfully */
}
7/21/2015
Ethan Cerami, NYU
17
Quick Review
/* Addition program */
#include <stdio.h>
#include <conio.h>
main()
{
int integer1, integer2, sum;
/* declaration */
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d\n", sum);
/*
/*
/*
/*
/*
/*
7/21/2015
Ethan Cerami, NYU
prompt */
read an integer */
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:
program description
author of program
date program was created
7/21/2015
Ethan Cerami, NYU
19
#include <conio.h>
As mentioned last time, the #include
statement includes another library so
that you can reuse its functionality.
conio.h: Console Input/Output
7/21/2015
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 ()
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.
7/21/2015
Ethan Cerami, NYU
21
Variable Declaration
/* Addition program */
#include <stdio.h>
#include <conio.h>
main()
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d\n", sum);
7/21/2015
/*
/*
/*
/*
/*
/*
/* declaration */
prompt */
read an integer */
prompt */
read an integer */
assignment of sum */
print sum */
Ethan Cerami, NYU
22
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!)
7/21/2015
Ethan Cerami, NYU
23
Basic Input: scanf ()
/* Addition program */
#include <stdio.h>
#include <conio.h>
main()
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
/* declaration */
/* prompt */
/* read an integer */
printf("Enter second integer\n"); /* prompt */
scanf("%d", &integer2);
/* read an integer */
sum = integer1 + integer2;
/* assignment of sum */
7/21/2015
Ethan Cerami, NYU
24
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.
7/21/2015
Ethan Cerami, NYU
25
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.
7/21/2015
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
integer1.
26
Two more tid-bits
/* Addition program */
#include <stdio.h>
#include <conio.h>
main()
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d\n", sum);
}
/* declaration */
/*
/*
/*
/*
/*
/*
prompt */
read an integer */
prompt */
read an integer */
assignment of sum */
print sum */
/* Wait for user to Any Key */
getch();
return 0; /* indicate that program ended successfully */
7/21/2015
Ethan Cerami, NYU
27
getch() Statement
getchar()
getch()
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.
7/21/2015
Ethan Cerami, NYU
28
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
7/21/2015
Ethan Cerami, NYU
29
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.)
7/21/2015
Ethan Cerami, NYU
30
Return 0
return 0 indicates that your program
ended successfully.
Hello World Program
“Hello Windows, everything ran
just fine”
Windows Operating
System
7/21/2015
Ethan Cerami, NYU
31
Basic Mathematical Operators
+ -Addition / Subtraction
* Multiplication
/
% Modulus Division
7/21/2015
Integer Division
Ethan Cerami, NYU
32
Integer Division - The Problem
Suppose you have the following code:
int x;
x = 7 / 4;
Using a calculator, the answer is 1.75.
But x can only hold integer values.
1.75 is clearly not an integer value.
7/21/2015
Ethan Cerami, NYU
33
Integer Division - Solution
To understand the solution, you need to
remember your 3rd Grade Math (really.)
1
4
7
4
The answer: 1 remainder 3
3
7/4 = 1 (Integer Division)
7%4 = 3 (Modulus Division)
7/21/2015
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: %d\n", x/y);
printf ("5%%10: %d\n", x%y);
getchar();
}
7/21/2015
Ethan Cerami, NYU
35
Modulus Division (cont.)
Second Example:
5/10 = 0
5%10 = 5
10
0
5
0
5
No matter what, you answers must be
integers.
7/21/2015
Ethan Cerami, NYU
36
Operator Precedence
Here’s another problem. What’s 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: 3*6 =18 7+18 = 25
Which option is correct? Clearly, we cannot have this
kind of ambiguity.
7/21/2015
Ethan Cerami, NYU
37
Operator Precedence
Rules for evaluating mathematical
expressions.
Every programming language has similar
rules.
From left to right:
7/21/2015
Parentheses are always evaluated first.
Multiplication, division and modulus are evaluated
next.
Addition and subtraction are evaluated last.
Ethan Cerami, NYU
38
Operator Precedence
Hence, option #2 is always correct:
x = 7 + 3 * 6;
Evaluates to x = 7 + 18 = 25
7/21/2015
Ethan Cerami, NYU
39
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:
7/21/2015
money
long distances
weight, etc.
Ethan Cerami, NYU
40
Float Example (Program 2.2)
/* Float Example Program */
#include <stdio.h>
main ()
{
float var1, var2, var3, sum;
var1 = 87.25;
var2 = 92.50;
var3 = 96.75;
%f: indicates floating
values
%.2f displays a floating
point value with 2 decimal
points.
Output:
Sum: 276.50
sum = var1 + var2 + var3;
printf ("Sum:
%.2f", sum);
getchar();
}
7/21/2015
Ethan Cerami, NYU
41
Challenge: Find an Average
Suppose you want to determine a student’s
average.
int num = 4;
float avg = 90+92+95+100/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 = (90+92+95+100)/num;
7/21/2015
Ethan Cerami, NYU
42
Finding an Average
Problem #2:
7/21/2015
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.
Ethan Cerami, NYU
43
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 = 90+92+95+100/num;
7/21/2015
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;
7/21/2015
Ethan Cerami, NYU
45