Chapter 02 - Fundamental Input Output and Basic C Operators
Chapter 02 - Fundamental Input Output and Basic C Operators
Department of Engineering 2
Basic Data Types
There are 4 basic data types :
int
float
double
char
int
Used to declare numeric program variables of integer type
Size in bits : 32
Range of values : -2147483648 to 2147483647
Whole numbers, positive and negative
Keyword: int
int number;
number = 12;
Department of Engineering 3
Basic Data Types (Cont.)
float
Fractional parts, positive and negative
Size in bits : 32
Range of values : 1.17e-38 to 3.4e+38 (accuracy up to 7 digits)
Keyword: float
float height;
height = 1.72;
double
Used to declare floating point variable of higher precision or
higher range of numbers
Size in bits : 64
Range of values : 2.2e-308 to 1.79e+308 (accuracy up to 15
digits)
Exponential numbers, positive and negative
Keyword: double
double valuebig;
valuebig = 12E-3;
Ref:
https://msdn.microsoft.com/en-us/library/hd7199ke.aspx
Department of Engineering 4
Basic Data Types (Cont.)
char
Equivalent to 'letters' in English language
Size in bits : 8
Range of values : -128 to +127
Example of characters:
Numeric digits: 0 - 9
Lowercase/uppercase letters: a - z and A - Z
Space (blank)
Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
Single character
Keyword: char
char my_letter;
The declared character must be
my_letter = 'U'; enclosed within a single quote!
Department of Engineering 5
Modifiers
Modifiers define the amount of storage allocated to the variable
Data type char, int, float, double have modifiers: short, long,
signed & unsigned
ANSI has the following rules:
short int <= int <= long int
float <= double <= long double
i.e. short int assigns less than or equal to amount of storage as an
int, and int assigns less than or equal to long int
Department of Engineering 6
Input/Output Operations
Input operation
An instruction that copies data from an input
device into memory
Output operation
An instruction that displays information stored
in memory to the output devices (such as the
monitor screen)
Department of Engineering 7
Input/Output Functions
A C function that performs an input or
output operation
Common input/output functions are
provided as part of C’s standard
input/output library. To access it:
#include <stdio.h>
Department of Engineering 8
The printf Function
printf("The area is %d.\n", area);
The printf function is called in order to display
program output
Inside the parenthesis are the functions
arguments
The arguments of printf include a format string
(given in quotes) followed by a print list
If the variable area has a value 24, above
function call displays the line:
The area is 24.
Department of Engineering 9
The printf Function (Cont.)
Function name
Placeholder Print list
Format string
Function arguments
Department of Engineering 10
The printf Function (Cont.)
Placeholder
a symbol beginning with %
indicate where to display the output value
Newline escape sequence
the character sequence \n
used in a format string to terminate an output
line
Department of Engineering 11
Format Specifier (Placeholder) in
Format String
It tells the printf( ) function the format of the
output to be printed onto the screen
Different conversion characters are used in
placeholders for different variable types
Department of Engineering 12
Escape Sequence
\n new line
\t tab
\r carriage return
\a alert
\\ backslash
\" double quote
Department of Engineering 13
Syntax Display for Function Call
Syntax:
printf(format string, print list);
printf(format string);
Format String is a combination of characters,
format specifier and escape sequence
Print List is any constants, variables, expressions,
and functions calls separated by commas
Examples:
printf("I am %d years old, and my gpa is %f\n", age,
gpa);
printf("Enter the object mass in grams> ");
Department of Engineering 14
Examples
This code:
Department of Engineering 15
Examples on Formatted printf
Statements
Department of Engineering 16
The Input Function scanf( )
Read data from the standard input device (usually keyboard)
and store it in a variable
The general format is pretty much the same as printf( )
function.
Syntax
scanf(Format String, Input List);
The format string has a similar structure to the format string in
printf( )
Input List – one or more variables addresses, each
corresponding to a format specifier in the Format String
One format specifier for each variable in Input List
The two or more variables in Input List must be separated
by commas
The placeholders in the format string must correspond to the
order of the variables in the input list
Each element of Input List must be an address of a memory
location (using prefix &Department
address operator)
of Engineering 17
scanf( ) Function
When scanf executed, the program pauses until
requested data is entered and the <return> or
<enter> key pressed
If too much data provided, the extra characters
will be saved for the next call to scanf
If not enough data provided, program will
continue to pause until more data entered and
<return> or <enter> key again pressed
If wrong type of data (characters when numeric
required) error occurs
Department of Engineering 18
Examples of Input
Many of the same formatting characters
are available for user input
scanf("%c", &nextChar);
Reads a single character and stores it in
nextChar
scanf("%f", &radius);
Reads a floating point number and stores it in
radius
Department of Engineering 19
Examples of Input (Cont.)
scanf("%d %d", &length, &width);
Reads two decimal integers (separated by
whitespace), stores the first one in length and
the second in width
Must use ampersand (&)for variables being
modified
Department of Engineering 20
Scanf( ) Function
Recognizing Data
char a;
int n, m;
double x, y;
input line n 25
25 62.91 36B x 62.91
m 36
scanf("%d%lf%d%c",&n,&x,&m,&a); a 'B'
x 25.0
scanf("%lf%d%c%d%lf", n 62
&x,&n,&a,&m,&y); a '.'
m 91
Note: The character B is left for the next y 36.0
scanf request
Department of Engineering 21
Most Common scanf Mistake
int x, y;
printf("Input (x, y) values:");
scanf("%d %d", x, y);
Must be &x, &y
Literals in format string must match literals in the
input stream
scanf("%s %d/%d/%d %lf",
name, &month, &day, &year, &gpa);
Department of Engineering 23
Constants (Cont.)
Integer constants
Positive or negative whole numbers with no fractional
part
Example:
const int MAX_NUM = 10;
const int MIN_NUM = -90;
Floating-point constants
Positive or negative decimal numbers with an integer
part, a decimal point and a fractional part
Example:
const double VAL = 0.5877e2;
(stands for 0.5877 102)
Department of Engineering 24
Constants (Cont.)
Character constants
A character enclosed in a single quotation mark
Example:
const char LETTER = 'n';
const char NUMBER = '1';
But, to print single quotation mark ' require backslash
(known as escape sequence) since ''' is illegal
printf("%c", '\'');
Prints a single quotation mark on screen
printf("%c", 'n');
Prints the letter n on the screen
printf("%c", '\n');
Move cursor to the beginning of a new line
Department of Engineering 25
Constant Example 1
#include <stdio.h>
int main(){
const double KMS_PER_MILES = 1.609;
double miles, kms;
Department of Engineering 26
Constant Example 2
#include <stdio.h>
#define KMS_PER_MILES 1.609
int main(){
double miles, kms;
Department of Engineering 27
Assignment Statements
An assignment statement in C assigns a value to a variable.
An assignment statement has the format:
variable = expression;
The name of the variable being modified is specified on the
left hand side of the equal sign. The expression on the right
can be a constant value, an algebraic equation, the return
value of a function, etc.
Some examples of assignment statements:
x = 2;
y = x + 2;
area = pi * radius * radius;
ch = getchar();
In addition to the equal sign (=), there are more advanced
assignment operators, which will be described later
Department of Engineering 28
Arithmetic Operators
There are 2 types of arithmetic
operators in C:
Unary operators
Operators that require only one operand
Binary operators
Operators that require two operands
Department of Engineering 29
Unary Operator
C Operation Operator Example
Positive + a = 3
Negative - b = -a
Increment ++ i++
Decrement -- i--
Department of Engineering 30
Binary Operators
The arithmetic operations are all binary, i.e., they require
two operands
Department of Engineering 32
Increment and Decrement
Operators (Cont.)
Consider the following segment of code
int a, x; //line 1
a = 3; //line 2
x = a++; //line 3 (suffix)
Department of Engineering 34
Assignment Operators
Assignment operators are used to combine the '=' operator
with one of the binary arithmetic operators
In the following slide, All operations starting from c = 9
Department of Engineering 35
Equal and Relational Operators
The relational operators are used to compare values
forming relational expressions
The logical operators are used to connect relational
expressions together using the rules of formal logic
Both types of expressions produce TRUE or FALSE results
Department of Engineering 36
Logical Operators
Logical operators are useful when we want to test
multiple conditions
There are 3 types of logical operators and they
work the same way as the boolean AND, OR and
NOT operators
&& - Logical AND
All the conditions must be true for the whole expression
to be true
Example: if (a == 10 && b == 9 && d == 1)
Means the if statement is only true when a == 10 and
b == 9 and d == 1
A B A&&B A||B
T T T T
T F F T
F T F T
F of Engineering
Department F F F 37
Logical Operators (Cont.)
|| - Logical OR
The truth of one condition is enough to make the whole
expression true
Example: if (a == 10 || b == 9 || d == 1)
Means the if statement is true when either one of a, b
or d has the right value
! - Logical NOT (also called logical negation)
Reverse the meaning of a condition
Example: if (!(points > 90))
Means if points not bigger than 90
Department of Engineering 38
Type Casting
C is a hard-typed language, meaning that each variable has
a fixed type that does not change
C provides a mechanism which allows the programmer to
change the default data type of a given arithmetic
expression to another using what is called a type cast
The general form of a cast is :
(type-name) expression
Where, type-name is the desired standard C data types; the
expression may be a constant, variable or an expression
Example: x = (float) 5; // results in 5.0
Especially useful for division, for example:
int totalScore, totalGrades;
totalScore / totalGrades; // would produces an integer
result
(float) totalScore / totalGrades casts totalScore to a
floating point number, then division would produce a
decimal point result
Department of Engineering 39
Type Casting Example
/* Computes a test average */
#include <stdio.h>
int main(){
int total_score, num_students;
float average;
Department of Engineering 42
Conditional Operator (Cont.)
Example 2:
if/else statement:
Conditional Statement:
Department of Engineering 44