0% found this document useful (0 votes)
64 views

Chapter 02 - Fundamental Input Output and Basic C Operators

This document discusses fundamental input/output and basic C operators. It covers bits and bytes, basic data types like int, float, double, and char, modifiers, input/output functions like printf and scanf, format specifiers, and examples of using printf and scanf. The key functions covered are printf for output and scanf for input, including their syntax and use of format strings and variables. Common mistakes with scanf like omitting the address of operator for variables are also noted.

Uploaded by

Ted Chan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Chapter 02 - Fundamental Input Output and Basic C Operators

This document discusses fundamental input/output and basic C operators. It covers bits and bytes, basic data types like int, float, double, and char, modifiers, input/output functions like printf and scanf, format specifiers, and examples of using printf and scanf. The key functions covered are printf for output and scanf for input, including their syntax and use of format strings and variables. Common mistakes with scanf like omitting the address of operator for variables are also noted.

Uploaded by

Ted Chan
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter 02 – Fundamental Input

Output and Basic C Operators


Bit and Byte
 Each piece of information stored within
computer's memory is encoded as some
unique combination of zero and ones
 These 0/1 are called bits
 1 byte = 8 bits

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.)

printf ("That equals %f kilometers.\n", kms) ;

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

Format Specifier Output Type


%d For integers
%c For characters
%f, %lf For floating-point values in conventional
notation
%s For sequence of characters (string)

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:

 produces this output:

Department of Engineering 15
Examples on Formatted printf
Statements

int a = 5; int b = 10; 123456789012345


printf("%d\n", a); 5
printf("%5d\n", a); 5
printf("%5d\n", b); 10
printf("%d %d\n", a, b); 5 10
printf("a = %d b = %3d\n", a, b); a = 5 b = 10

float x = 33.3456789; 123456789012345


printf("%f\n", x); 33.345679
printf("%8.3f\n", x); 33.346

printf(“|%s|", "hello, world"); |hello, world|

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);

Must input as David 7/24/2012 3.83


Variables of type int, float or char need &
Do NOT use & with strings!
Department of Engineering 22
Constants
 Entities that appear in the program code
as fixed values
 Example:
const double INTEREST_RATE = 0.015;
 4 types of constants:
 Integer constants
 Floating-point constants
 Character constants
 Enumeration (we won’t cover this topic in our
module)

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;

printf("Enter the distance in miles:");


scanf("%lf", &miles);

kms = KMS_PER_MILES * miles;


printf("\nThat equals %f kilometer.\n", kms);
return 0;
}

Department of Engineering 26
Constant Example 2
#include <stdio.h>
#define KMS_PER_MILES 1.609
int main(){
double miles, kms;

printf("Enter the distance in miles:");


scanf("%lf",&miles);

kms = KMS_PER_MILES * miles;


printf("\nThat equals %f kilometer.\n", kms);
return 0;
}

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

 The first assigns positive 3 to a


 The second assigns the negative value of a to b
 i++ is equivalent to i = i + 1
 i-- is equivalent to i = i - 1

Department of Engineering 30
Binary Operators
 The arithmetic operations are all binary, i.e., they require
two operands

 The division of variables of type int will always produce a


variable of type int as the result
 The modulus operator can only be used with integers. The
expression x % y yields the reminder of the division of x by
y
 For example 7 % 4 is equal to 3
Department of Engineering 31
Increment and Decrement
Operators
 Both increment and decrement operators can be used as a
prefix (pre) or as a suffix (post). The operator can be
written before the identifier as a prefix (++a) or after the
identifier as a suffix (a++)
 In simple operations such as a++ or ++a both have
exactly the same meaning. However in some cases there is
a difference
 Consider the following set of statements:
int a, x; //line 1
a = 3; //line 2
x = ++a; //line 3 (prefix)
 After executing above segment of code, "a" will be 4 and
"x" will be 4
 In line 3, first the variable "a" is incremented before
assigning it to variable "x"

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)

 After executing above code segment "a" will


be 4 and "x" will be 3
 In the second approach in line 3 first "a" is
assigned to "x" and then "a" is
incremented
Department of Engineering 33
Increment and Decrement
Operators (Cont.)
0

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;

printf("Enter sum of students' scores> ");


scanf("%d", &total_score);
printf("Enter number of students> ");
scanf("%d", &num_students);
average = (double) total_score / num_students;
printf("Average score is %.2f\n", average);
return 0;
}
Department of Engineering 40
Conditional Operator
 The conditional operator (? :) is used to simplify
an if/else statement
 Takes three arguments (condition, value if true, value if
false)
 Syntax:
Condition ? Expression1 : Expression2
 If the condition is TRUE the result return Expression1 and if
not it returns Expression2
 The statement above is equivalent to:
if (Condition)
Expression1
else
Expression2 Department of Engineering 41
Conditional Operator (Cont.)
 Example 1:
if/else statement:
if (total >= 60)
grade = 'P'
else
grade = 'F';
conditional statement:
grade = total >= 60 ? 'P' : 'F';

Department of Engineering 42
Conditional Operator (Cont.)
 Example 2:
if/else statement:

if (total >= 60)


printf("Passed!!\n");
else
printf("Failed!!\n");

Conditional Statement:

printf("%s!!\n", total >= 60? "Passed" : "Failed");


Department of Engineering 43
Types of Errors
 Syntax errors - ( compilers / interpreters)
 These errors are generated if the rules of the language
defined are not followed
e.g.: Missing of a semicolon after an assignment
operation
 Logical errors - ( debugger)
 They are also referred to as semantic errors, and these
result if the desired outputs are not obtained
 Run Time errors -
 These occur when a program attempts to perform a task
which is forbidden
 Examples of run time errors:
 Null pointer assignment
 Divide by zero

Department of Engineering 44

You might also like