Sie sind auf Seite 1von 50

CS113: Introduction to Programming

Lecture 4

Todays Lecture
Input function
Output function
Variables
Operators
Input / Output
I/O
Output printf ()
Input scanf ()
printf() function
printf ( String constant , additional arguments);
optional
print formatted
1. Displays text put inside the double quotes
2. Requires backslash character - an escape sequence -
to display some special characters e.g. \n
3. Uses conversion specifier % character as a place
holder to be filled during printing
4. Returns the number of characters printed


printf()
"% format specifier
specify both the relative location and the
type of output that the function should
produce

A literal percent sign can be copied into the
output using the escape sequence %%

printf() Example
printf(sum = %d, 3+5) ;

Output: sum = 8
Conversion specifiers

Conversion Character Displays Argument
(Constant or Variables Contents) as
%c Single character
%d Integer
%e Floating point value in E notation
%f Floating point value (with decimal)
%lf Double
%s String of text
Data Types

Data Types
Field width specifier
%5f
f floating point number (decimal no.)
5 imaginary box preceding decimal point

%.2f
.2 No. of decimal places to the right of
decimal point

What will %4.3 do?


Be careful !!!
printf(%d %d, i ) ; // Extra specifier

printf(%d, i, j) ; // Extra variables

printf(%f %d, i, j) ; // int i, float j ---
//meaningless output

No compilation error
Escape Sequences
Added within strings
Performs special printing
\n newline
\r carriage return (not common)
\t tab
\a alert (beep)
\\ backslash
\ single quote
\ double quote

scanf()
Like a pattern-matching function
Matches input with conversion specifiers
Ignores white-space characters
Space, tab, new line character
scanf () Example
printf(Enter the value of integer);

scanf( "%d", &integer );
scanf(%d%d%f%f, &i, &j, &x, &y);
Input by user: 1 -20 .3 -4.0e3

Common mistake: Skipping the &
symbol
scanf() function
scanf( "%d", &num );
Obtains a value from the user
scanf uses standard input (usually keyboard)
This scanf statement has two arguments
%d - indicates data should be a decimal integer
&num - location in memory to store variable
& is confusing in beginning for now, just remember to
include it with the variable name in scanf statements
When executing the program the user responds to the
scanf statement by typing in a number, then pressing
the enter (return) key Ref: Deitel & Deitel

scanf() example
int a;

scanf( %d , &a);

scanf(%d %d, &a, &b);
1 /*
2 Addition program : Adding two numbers */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main()
7 {
8 int integer1; /* first number to be input by user */
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
11
12 printf( "Enter first integer\n" ); /* prompt */
13 scanf( "%d", &integer1 ); /* read an integer */
14
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
17
18 sum = integer1 + integer2; /* assign total to sum */
19
20 printf( "Sum is %d\n", sum ); /* print sum */
21
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */
Output
Enter first integer
45
Enter second integer
72
Sum is 117

Variable
Variable x
x = 5

Location in memory where a value can be stored
You may retrieve or modify them when necessary

Variable name (Identifier)
Small mailbox (memory)








x
5
Integer Variables
int means the variables can hold integers
or whole numbers (-1, 3, 0, 47)

int x; // Declaration statement
(Memory is set aside for x at some address)

An integer variable is a variable that can
only hold an integer value.



Variables Assignment
Definitions appear before executable
statements
If an executable statement references an
undeclared variable it will produce a
syntax (compiler) error

x = 10; int x;
int x; x = 10;
// Error // Correct



Variable names (Identifiers)
A variable name must begin with a
1. Letter
2. Underscore _ (Not Recommended)
3. The rest can be letters, digits, and
underscores

Can be of any length, first 31 are significant
(too long is as bad as too short).

Are case sensitive:
abc is different from ABC
Variable
In a program a variable has:
1. Name
2. Type
3. Size
4. Value

integer1 45
integer2 72
sum 117
Assignment Operator =
Assigns a value to a variable
Is a binary operator (has two operands)
sum = variable1 + variable2;
sum gets variable1 + variable2;
Variable receiving value on left
printf( "Sum is %d\n", sum );
Similar to scanf()
%d means decimal integer will be printed
sum specifies what integer will be printed
Calculations can be performed inside printf
statements
printf( "Sum is %d\n", integer1 + integer2 );

Assignment Operator
=
x = 2

X
2
L-value
Variables are also known as l-values.
L-values are values that can be on the
left side of an assignment statement.
When we do an assignment, the left
hand side of the assignment operator
must be an l-value.
Assignment Operator
5 = 6 Incorrect
X + 3 = y + 4 Incorrect
Z = x + 4 Correct
x + 4 = Z Incorrect

X = 10 ;

X = 30 ;



Reading variables from memory does not change them

X
10
X
30
When an l-value has a value
assigned to it, the current value is
overwritten.
X = X + 1;
10
+1
=
X
11
R-values (Opposite of L-values)

An r-value refers to any value that can be
assigned to an l-value.
R-values are always evaluated to produce
a single value.
Examples
Single numbers (5, which evaluates to 5)
Variables (x, which evaluates to whatever
number was last assigned to it)
Expressions (2+x, which evaluates to the last
value of x plus 2).
#include <stdio.h> // Pre-processor directive

int main ( ) //Starting point of your program
{
int x ;
int y ;
int z ;
x = 10 ; // Assigns value 10 to x
y = 20 ; // Assigns value 20 to y
z = x + y ; // Adds x and y and assigns to z

printf( " x = %d ", x ); //Prints x = 10 on the monitor

printf( " y = %d ", y ); //Prints y = 20 on the monitor

prinft( " z =x + y = %d", z); // Prints z = x + y = 30
}

int x, y, z ;
int x; int y; int z ;

Variable declaration
Initialize Variables
int x; // Variable declaration
int x = 0; // Initialization

Rule: Always assign values to your
variables when you declare them.
Arithmetic Operators
Arithmetic operators
i + j
x * y
a / b
a % b

% = Remainder
5 % 2 = 1
2 % 2 = 0

Modulus operator returns remainder

4 / 2 = 2
5 / 2 = 2

Integer division truncates remainder
/ = Division
Arithmetic Expressions
Operator Precedence
Some arithmetic operators act before
others (i.e., multiplication before
addition)
Use parenthesis when needed
Example: Find the average of three
variables a, b and c
Do not use: a + b + c / 3
Use: (a + b + c ) / 3

Order of Evaluation (Precedence)
Operator Precedence
Highest: ( )
Next: * , / , %
Lowest: + , -
Decision making: Equality
& relational operators
Executable statements
Perform actions (calculations, input/output of
data)
Perform decisions
May want to print "pass" or "fail" given the value of
a test grade
if control statement
Simple version in this section, more detail later
If a condition is true, then the body of the if
statement executed
0 is false, non-zero is true
Control always resumes after the if structure

Decision making: Equality &
relational operators

1 /* Using if statement, relational operators,
2 and equality operators */
3
4 #include <stdio.h>
5
6 /* function main begins program execution */
7 int main()
8 {
9 int num1, /* first number to be read from user */
10 int num2; /* second number to be read from user */
11
12 printf( "Enter two integers, and I will tell you\n" );
13 printf( "the relationships they satisfy: " );
14
15 scanf( "%d%d", &num1, &num2 ); /* read two integers */
16
17 if ( num1 == num2 ) {
18 printf( "%d is equal to %d\n", num1, num2 );
19 } /* end if */
20
21 if ( num1 != num2 ) {
22 printf( "%d is not equal to %d\n", num1, num2 );
23 } /* end if */
25 if ( num1 < num2 ) {
26 printf( "%d is less than %d\n", num1, num2 );
27 } /* end if */
28
29 if ( num1 > num2 ) {
30 printf( "%d is greater than %d\n", num1, num2 );
31 } /* end if */
32
33 if ( num1 <= num2 ) {
34 printf( "%d is less than or equal to %d\n", num1, num2 );
35 } /* end if */
36
37 if ( num1 >= num2 ) {
38 printf( "%d is greater than or equal to %d\n", num1, num2 );
39 } /* end if */
40
41 return 0; /* indicate that program ended successfully */
42
43 } /* end function main */

Precedence and Associativity of
operators
Keywords in C

Cannot be used as variable names
Summary
Input
Output
Variables
Operators

Das könnte Ihnen auch gefallen