C02
“ Programming
Fundamentals
PROBLEM SOLVING AND PROGRAM DESIGN IN C BY HANLY AND KOFFMAN ”
Objectives:
Be able to recognize the structure of C program
Be able to apprehend the use of variables and constants
Be able to realize the use of data types
Be able to learn different operators and their precedence rules
Instructor: Aatif Shahbaz 1
CLO_1
Programming
Fundamentals Contents:
Structure of C programs
Chapter 2
Constants and Variables
Problem Solving and Program
Design in C by Hanly and Data Types
Koffman Standard Output – printf( )
Standard Input – scanf( )
Operators and Precedence
Instructor: Aatif Shahbaz
C02
Lecture 03
STRUCTURE OF C PROGRAM. HELLO WORLD EXAMPLE
Structure of C Program
Instructor: Aatif Shahbaz 4
Preprocessor Directives
The C program has two parts: preprocessor directives and the main function.
The preprocessor directives are commands that give instructions to the C preprocessor.
Its job it is to modify the text of a C program before it is compiled.
A preprocessor directive always begins with a symbol #.
Instructor: Aatif Shahbaz 5
The main( ) Function
The heading [ int main(void) ] marks the beginning of the main function where program execution begins.
Every C program has a main function.
The remaining lines of the program form the body of the function which is enclosed in braces { }.
Example: Hello World
Instructor: Aatif Shahbaz 6
Reserved Words
Each line of previous code contains a number of different words classified as reserved words, identifiers from
standard libraries, and names for memory cells.
All the reserved words appear in lowercase; they have special meaning in C and cannot be used for other
purposes.
Library:
A collection of useful predefined functions and symbols that may be accessed by a program.
Instructor: Aatif Shahbaz 7
User-Defined Identifiers
We can choose our own identifiers (called user-defined identifiers ) to name memory cells that will hold data
and program results and to name operations that we define.
You have some freedom in selecting identifiers. The syntax rules are as follow.
An identifier must consist only of letters, digits, and underscores.
An identifier cannot begin with a digit.
A C reserved word cannot be used as an identifier.
An identifier defined in a C standard library should not be redefined.
Following are Valid Identifiers:
letter_1, inches, cent, CENT_PER_INCH, Hello, variable
C language is case sensitive, hence Rate, rate, and RATE are viewed by compiler as different identifiers.
Following are some invalid identifier
1Letter : must begins with a letter
double, int : reserved word
joe’s : character ’ not allowed
Instructor: Aatif Shahbaz 8
C02
Lecture 04
CONSTANTS AND VARIABLES. DATA TYPES. STANDARD OUTPUT.
Variable Declarations
The memory cells used for storing a
program’s input data and its
computational results are called
variables.
They also tell the compiler what
kind of information will be stored in
each variable and how that
information will be represented in
memory.
A variable declaration begins with
an identifier (for example, int, float,
char) that tells the C compiler
which type of data stored in a
particular variable.
C requires you to declare every
variable, before accessing it in a
program.
Instructor: Aatif Shahbaz 10
Data Types
A data type is a set of values and a set of operations on those values.
Knowledge of the data type of an item (a variable or value) enables the C compiler to correctly specify
operations on that item.
A standard data type in C is a data type that is predefined, such as char, float and int.
int as abstraction for whole numbers – (size 4 bytes)
float as abstraction for decimal numbers – (size 4 bytes)
char as abstraction for single alpha-numeric character – (size 1 byte)
Objects of a data type can be variables or constants.
Variable :
A name associated with a memory cell whose value can be changed.
Constant :
A name associated with a memory cell whose value cannot be changed.
Read the topic Main Memory from section 1.2 (Computer hardware).
Instructor: Aatif Shahbaz 11
Fundamental Data Types In C
Instructor: Aatif Shahbaz 12
Data Type char
Data type char represents an
individual character value - a
letter, a digit, or a special symbol.
Each type char value is
enclosed in apostrophes (single
quotes)
'A' 'z' '2' '9' '*' ':' ' ‘
ASCII Code :
American Standard Code for
Information Interchange
You should know that a character
is represented in memory as an
integer(binary).
The value stored is determined by
the code used by your C
compiler.
Instructor: Aatif Shahbaz 13
Assignment Statements
An instruction that stores a value or a computational result in a variable.
Examples:
kms = KMS_PER_MILE * miles;
The char variable xyz is assigned the character value ‘A’ by the assignment statement:
A single character variable or value may appear on the right-hand side of a character assignment
statement.
Example :
xyz = ‘A’ ;
Instructor: Aatif Shahbaz 14
Standard Output – printf( )
The most common input/output functions are supplied as part of the C standard input/output library to
which we gain access through the preprocessor directive #include <stdio.h>
This statement calls function printf(pronounced “print-eff”) to display a line of program output.
A function call consists of two parts: the function name and the function arguments, enclosed in
parentheses.
The arguments for printf consist of a format string (in quotes) and a print list (the variable kms ).
Output : That equals 16.090000 kilometers.
The function call above displays the above line which is the result of displaying the format string "That equals
%f kilometers.\n" after substituting the value of kms for its placeholder ( %f ) in the format string.
Instructor: Aatif Shahbaz 15
The Placeholder
A placeholder always begins with the symbol % .
Here the placeholder %f marks the display position for a type float/double variable.
Table below shows placeholders for type char, float and int variables.
Each placeholder is an abbreviation for the type of data it represents.
Multiple Placeholders:
Format strings can have multiple placeholders.
If the print list of a printf call has several variables, the format string should contain the same number of
placeholders.
C matches variables with placeholders in left-to-right order.
Instructor: Aatif Shahbaz 16
Formatting Numbers in Program Output
C displays all numbers in its default notation unless you instruct it to do otherwise.
Explore Yourself
NOTE: Read section 2.6
Formatting Values of Type double
Instructor: Aatif Shahbaz 17
C02
Lecture 05
STANDARD INPUT. PROGRAMMING WITH VARIABLES.
Standard Input – scanf( )
The statement [ scanf("%f", &miles) ] calls function scanf(pronounced “scan-eff”) to copy data into the
variable miles .
It copies the data from the standard input device.
In most cases the standard input device is the keyboard.
Consequently, the computer will attempt to store in miles.. whatever, data the program user types at the
keyboard.
Notice that in a call to scanf, the name of each variable that is to be given a value is preceded by the
ampersand character (&), address-of operator.
In the context of this input operation, the & operator tells the scanf function where to find each variable to
store a new value.
If the ampersand were omitted, scanf would know only a variable’s current value, not its location in memory,
so scanf would be unable to store a new value in the variable.
Instructor: Aatif Shahbaz 19
Comments
Comments are parts of the source code ignored by the compiler. They simply do nothing. Their purpose is
only to allow the programmer to insert notes or descriptions embedded within the source code.
C supports two ways to insert comments:
Line Comment //
Block Comment /* …. */
Instructor: Aatif Shahbaz 20
Initialization Of Variables
Examples: Swapping initial value of two variables
Instructor: Aatif Shahbaz 21
Programming With Variables
Examples: Swapping with or without 3rd variable
Instructor: Aatif Shahbaz 22
Programming With Variables
Instructor: Aatif Shahbaz 23
Escape Characters
These are special characters that are difficult or impossible to express otherwise in the source code of a
program.
All of them are preceded by a backslash (\).
Explore Yourself
Instructor: Aatif Shahbaz 24
C02
Lecture 06
OPERATORS AND PRECEDENCE.
Arithmetic Operators
The five arithmetical operations supported by the C language are:
Addition ( + )
Subtraction ( - )
Multiplication ( * )
Division ( / )
Modulo ( % )
Compound Assignment Operators:
When we want to modify the value of a variable by performing an operation on the value currently stored in
that variable we can use compound assignment operators:
Instructor: Aatif Shahbaz 26
Division Operator “/”
Observe the results of the arithmetic statements shown below.
It has been assumed that k is an integer variable and a is float variable.
Examples:
Instructor: Aatif Shahbaz 27
Modulo Operator “%”
The mod operator ( % ) returns the integer remainder of the result of dividing its first operand by its second.
Examples:
Instructor: Aatif Shahbaz 28
Increment And Decrement (++, --)
++ and -- are equivalent to +=1 and to -=1 respectively.
Thus above all are equivalent in its functionality: the three of them increase by one the value of c.
Examples:
In Example 1, B is incremented before its value is copied to A.
While in Example 2, the value of B is copied to A and then B is incremented.
Instructor: Aatif Shahbaz 29
Relational And Equality Operators
In order to evaluate a comparison between two expressions we can use the relational and equality
operators.
The result of a relational operation is a Boolean value that can only be TRUE or FALSE, according to its
Boolean result.
Examples:
Of course, instead of using only numeric constants, we can use any valid expression, including variables.
Suppose that a=2, b=3 and c=6
Instructor: Aatif Shahbaz 30
Logical Operators
The Operator ! is the C operator to perform the Boolean operation NOT, it has only one operand, located at
its right, and the only thing that it does is to inverse the value of it.
It produce false if its operand is true and true if its operand is false.
Example:
The operator && corresponds with Boolean logical operation AND.
This operation results TRUE if both its two operands are TRUE, FALSE otherwise.
The operator || corresponds with Boolean logical operation OR.
This operation results FALSE if both its two operands are FALSE, TRUE otherwise.
Example:
Instructor: Aatif Shahbaz 31
Conditional Operator
Its format is: condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return result2.
Example:
Bitwise Operators:
Bitwise operators modify variables considering the bit patterns that represent the values they store.
Instructor: Aatif Shahbaz 32
Precedence Of Operators
Precedence Operator Description Associativity
1 ++ -- Postfix increment and decrement Left-to-right
++ -- Prefix increment and decrement
+- Unary plus and minus
Right-to-left
2 !~ Logical NOT and bitwise NOT
3 */% Multiplication, division, and remainder
4 +- Addition and subtraction
5 << >> Bitwise left shift and right shift
< <= For relational operators < and ≤ respectively
6 > >= For relational operators > and ≥ respectively
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
Left-to-right
10 | Bitwise OR (inclusive or)
11 && Logical AND
12 || Logical OR
13 ?: Ternary conditional Right-to-Left
Instructor: Aatif Shahbaz 33
Precedence Of Operators
Precedence Operator Description Associativity
= Simple assignment
+= -= Assignment by sum and difference
*= /= %= Assignment by product, quotient, and remainder
14 Right-to-Left
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
When writing complex expressions with several operands, we may have some doubts about which operand
is evaluated first and which later.
Example:
a = 5 + 7 % 2 , We may doubt if it really means a = 5 + (7 % 2) = 6 OR a = (5 + 7) % 2 = 0
What if want are expecting opposite of what is evaluated ?
Thumb Rule:
Precedence levels for operators can be manipulated or become more legible by removing possible
ambiguities using parentheses signs ( ).
Instructor: Aatif Shahbaz 34
C02
Task 1:
Write a program that implements the following equation in C.
Prompt user about all input variables and display results to user once calculated.
Task 2:
Write a program to perform basic arithmetic operations which are addition,
subtraction, multiplication and division of two numbers.
Prompt user about two numbers and display results to user once calculated.
Assignment 2
Instructor: Aatif Shahbaz 35
C02
Do exercises for section 2.3 (Self-Check & Programming)
Do exercises for section 2.4 (Self-Check & Programming)
Do exercises for section 2.5 (Self-Check & Programming)
Do exercises for section 2.6 (Self-Check & Programming)
Practice Problems
Instructor: Aatif Shahbaz 36