C-Notes Unit 1,2,3

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 126

Topic 1: Introduction to

Computers and Programming

“A journey of a thousand miles must begin


with a single step.” - Lao Tzu
Binary Math
A binary digit or bit for short is the smallest unit of
computer information. Just as our familiar decimal
number system has 10 digits,(0,1,2,3,4,5,6,7,8,9) the
binary number system has only 2 digits (0,1). This is
the perfect number system for computers since we
can store a binary digit by making an electrical or
magnetic field either on or off, positive or negative, 1
or 0. In the decimal system we can count 10 (we
start counting with 0) items with one decimal place,
100 with two decimal places, 1000 with three decimal
places and so on.

CISC 105 – Topic 1 2


Binary Math
The binary number system works the same way except
since we only have 0s and1s our base is 2.

So we can count 2 permutations of 1 bit: 0 1


4 permutations of 2 bits: 00 01 10 11
8 permutations of 3 bits: 000 001 010 011 100 101 110
111
16 permutations of 4 bits: 0000 0001 0010 0011 0100
0101 0110 0111 1000 1001 1010 1011 1100 1101
1110 1111
...and so on.

CISC 105 – Topic 1 3


Binary Math
So in an eight bit byte, the numbers are represented this way:

Bit: - - - - - - - -
Value: 128 64 32 16 8 4 2 1

Example: 1 0 1 1 0 1 1 0

Values: 128 + 0 + 32 +16 + 0 + 4 + 2 + 0 = 182

The minimum number is 0 (all 0s) and the maximum number is


255 (all 1s), so you can represent 256 numbers (0-255) with
one byte.

CISC 105 – Topic 1 4


Hardware Components
■ Hardware consists of many types of
components:
■ Primary Storage
■ Secondary Storage
■ The Central Processing Unit (CPU)
■ Input Devices
■ Output Devices

CISC 105 – Topic 1 5


Primary Storage and
Secondary Storage
■ There are two primary types of storage
in a computer:
■ Primary Storage – often referred to as
main memory, or just memory. This
storage is very quickly accessed by the
various hardware components.
■ Secondary Storage – includes such devices
as a hard disk, floppy disk, CD-ROM, DVD-
ROM, etc…

CISC 105 – Topic 1 6


Computer Software
■ All major computers run an operating
system.
■ An operating system is a special type of
program which controls the interaction
between all hardware components and
the user.

CISC 105 – Topic 1 7


Operating Systems Tasks
■ Responsibilities of the OS include:
■ Communicating with the user(s)
■ Managing resources including memory and
processor time among programs
■ Collecting data from input devices
■ Providing data to output devices
■ Accessing data from secondary storage
■ Writing data to secondary storage

CISC 105 – Topic 1 8


Computer Programming -
Machine Language
■ Computer programs were originally written in
machine language. Machine language is a
sequence of binary numbers, each number
being an instruction.
■ Each instruction is computer-understandable.

00000000
00010101
00010110

CISC 105 – Topic 1 9


Computer Programming -
Assembly Language
■ To make machine language more abstract, assembly
language was introduced.
■ Assembly language provides a one-to-one mapping
between a machine instruction and a simple human-
readable instruction.
■ Assembly language is converted to computer-
understandable machine language by an assembler.

CLR A 00000000
ADD A 00010101
ADD B 00010110
CISC 105 – Topic 1 10
Computer Programming –
High-Level Languages
■ In order to get around these obstacles, high-
level languages were introduced.
■ High-level languages provide a one-to-many
mapping between one high-level statement
and multiple assembly language instructions.
■ High-level language is converted to assembly
instructions by a compiler, which creates
object files. Modern compilers perform the
assembler function as well.
CISC 105 – Topic 1 11
Modern Software
Development
■ Programmers often use library functions,
which are pre-written functions provided as
part of the compiler/development toolset.
■ A library is an object file.
■ After the source code is compiled into
machine code, a linker resolves cross-
references among these object files, including
libraries. The object files are linked into an
executable file.
CISC 105 – Topic 1 12
Modern Software
Development
Source Code File Compiler

Object File

Other Object
Files
(perhaps
Linker Executable File
libraries)

Loader

CISC 105 – Topic 1 13


The Software
Development Method
■ Specify the problem.
■ Analyze the problem.
■ Design an algorithm to solve the
problem.
■ Implement the algorithm.
■ Test and verify the program.
■ Maintain and update the program.

CISC 105 – Topic 1 14


Review
■ Name the principle components of a
computer.
■ What are three responsibilities of the
operating system?
■ What advantages does assembly language
have over machine language?
■ What advantages do high-level languages
have over assembly language?

CISC 105 – Topic 1 15


Review
■ What computer program translates a source
code file into an object file?
■ What program combines object files and
produces an executable file?
■ What part of the operating system is
responsible for the loading and scheduling of
programs?
■ What are the steps in the software
development method?

CISC 105 – Topic 1 16


Topic 2 – Introduction to the
C Programming Language
Preprocessor Directives
■ A preprocessor directive is a command given
to the C preprocessor, which is a part of the
compilation process that modifies a C source
code file before it is compiled.
■ Preprocessor directives always begin with a
“#” character.
■ In the example program, there are two
preprocessor directives used, #include and
#define.
CISC 105 – Topic 1 18
#include
■ The #include directive tells the C
preprocessor to give a program access to a
library. By putting a #include in a program,
the preprocessor loads a header file, which
tells the compiler what functions and other
information is provided in the library.
■ In this program, #include <stdio.h>
indicates that this program uses the stdio
library which contains functions such as
printf(). Page 542 of Deitel lists standard
libraries.
CISC 105 – Topic 1 19
#define
■ The #define directive specifies a constant
macro.
■ This tells the preprocessor that every time it
encounters the first text, it should replace it
with the second text.
■ In this program, #define KMS_PER_MILE 1.609
tells the preprocessor to replace
KMS_PER_MILE with 1.609 every place
KMS_PER_MILE appears in the program.
CISC 105 – Topic 1 20
Preprocessor Directives
/* Converts distances from miles to kilometers */

#include <stdio.h>
#define KMS_PER_MILE 1.609

int main(void)
{
double miles, /* distance in miles */
kms; /* equiv. distance in kms */
/* Get the distance in miles */
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles);

/* Convert the distance to kilometers */


kms = KMS_PER_MILE * miles;

/* Display the distance in kilometers */


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

return(0);
}
CISC 105 – Topic 1 21
Preprocessor Directives
#include directive –
/* Converts distances from miles to kilometers */

#include <stdio.h> Tells the preprocessor to


#define KMS_PER_MILE 1.609 include the stdio.h header file.
int main(void) This file describes the
{
double miles, /* distance infunctions
miles */
and other information included
kms; /* equiv. distance in kms */
/* Get the distance in miles */
in the stdio library.
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles);

/* Convert the distance to kilometers */


kms = KMS_PER_MILE * miles;

/* Display the distance in kilometers */


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

return(0);
}
CISC 105 – Topic 1 22
Preprocessor Directives
#include directive –
/* Converts distances from miles to kilometers */

#include <stdio.h> Tells the preprocessor to


#define KMS_PER_MILE 1.609 include the stdio.h header file.
int main(void) This file describes the
{
double miles, /* distance infunctions
miles */
#define directive –
and other information included
kms; /* equiv. distance in kms */
Tells
/* Get the distance in miles */ the preprocessor to
in the stdio library.
printf(“Enter the distance in miles>”);
scanf (“%lf”, &miles); replace every occurrence of
/* Convert the distance to KMS_PER_MILE
kilometers */ in the
kms = KMS_PER_MILE * miles;
program
/* Display the distance in with 1.609.*/
kilometers
printf (“That equals %f kilometers.\n”,kms);

return(0);
}
CISC 105 – Topic 1 23
What is a valid identifier?
■ Identifiers can only be composed of
letters, digits, and underscores.
■ Identifiers cannot begin with a digit.
■ Reserved words cannot be identifiers.
■ Identifiers can be as long as you want.
■ Upper and lower case letters are
different (i.e. kms and Kms are not
considered to be the same identifier).

CISC 105 – Topic 1 24


Review
■ Which of the following are valid identifiers?
For each that is not valid, why is it not?

This_is_a_long_identifier_but_is_it_valid
?8timesTheRadius
miles
Phil’s variable
kilometers_per_hou
xr
“radius”

CISC 105 – Topic 1 25


Variables
■ A variable is a memory cell that is used to
hold data acted upon by the program.
■ A variable declaration tells the C compiler the
name and type of a variable used in a
program.
■ A variable declaration consists of a data type
and an identifier which is the name of that
variable.
■ Every variable that will be used in a program
must be declared.
CISC 105 – Topic 1 26
Variable Declarations

double mile;
int counter;

■ The first line declares a variable named


mile of the double data type.
■ The second line declares a variable
named counter of the int data type.

CISC 105 – Topic 1 27


Data Types
■ There are a large number of data types.
These are some of the most popular ones.
■ void – this keyword means “no data type”.
■ int – An integer (a whole number). This
data type can represent an integer in a
specific range, at least –32767 through
32767.

CISC 105 – Topic 1 28


Data Types
■ char – A character. One letter, digit, or
symbol. This is enclosed in single quotes.
■ float – A real number (an integer part and
a decimal part).
■ double – A real number. Note that this data
type is a memory cell double the size of a
float data type. This allows a bigger
number to be represented, or a specific
number to be represented more precisely.
This is referred to as a double-precision
floating point number.
CISC 105 – Topic 1 29
Review of Variables
■ Write a #define preprocessor declaration for a
constant macro of STUDENTS_PER_SECTION to 22
and variable declarations of num_students as an
integer, GPA and class_GPA as double-precision
floating point numbers, and letter_grade as a
character data type.

#define STUDENTS_PER_SECTION 22

int num_students;
double GPA, class_GPA;
char letter_grade;
CISC 105 – Topic 1 30
Assignment Statements
■ An assignment statement is one type of
executable statement.
■ An assignment statement uses the “=“
operator, and follows the form:
variable =
expression;
■ This statement first evaluates the
expression on the right and stores the
result in the variable on the left.
CISC 105 – Topic 1 31
Assignment Statements
■ Here are some examples of assignment
statements:
■ x = 12;
■ negative_x = -x;
■ x = y + 12 + z * 5;
■ result = y;
■ Note that any variables in the right-side
expression are not modified by an assignment
statement.

CISC 105 – Topic 1 32


Function Calls
■ A function is a piece of code which performs
a specific task.
■ Functions can be created by programmers or
supplied as part of the C compiler toolset.
■ A function is called, which causes it to
execute.
■ A function call is composed of the function
name, an open paren, a set of function
arguments separated by commas, and a close
paren.
CISC 105 – Topic 1 33
Function Calls
■ A function call looks like this:
function_name(argument1, argument2, argument3);

function function
name arguments

open close paren


paren

CISC 105 – Topic 1 34


The printf Function
■ The C function for displaying output on
the screen to the user is printf.
■ printf is called in the following manner:
printf(“The final GPA of student number %d is %f.\n”,student_num,
GPA);

format print
string list

function
arguments
CISC 105 – Topic 1 35
The Format String
and Print List
■ The format string is the text that is to be
displayed on the screen.
■ The “%” characters are called placeholders.
They indicate the display position for
variables whose values are to be displayed.
■ The variable names to be displayed are
specified in the print list and appear in the
same order as their placeholders.

CISC 105 – Topic 1 36


Placeholders
printf(“The final GPA of student number %d is %f.\n”,student_num,
GPA);

This pair specifies the location in the print


string to display the student_num value.

This pair specifies the location in the print


string to display the GPA value.

CISC 105 – Topic 1 37


Placeholders
■ All placeholders begin with a “%”.
■ The text after the “%” symbol indicates
how to format the output, i.e. what kind
of variable it is.
■ %d – decimal number (int)
■ %f – floating-point number (float or
double)
■ %c – character (char)

CISC 105 – Topic 1 38


Escape Sequences
■ All escape-sequences begin with a backslash,
“\”.
■ A letter after the “\” character denotes an
escape sequence, which has special meaning.
■ The “\n” sequence indicates a new-line
character, which cause any following text to
appear on the next line on the display.
■ In order to display a “\”, the format string
must contain a “\\”.

CISC 105 – Topic 1 39


Placeholders and the
Newline Escape Sequence
printf(“The final GPA of student number %d is %f.\n”,student_num,
GPA);

Specifies to display student_num,


which is an integer.

Specifies to display GPA,


which is an floating-point number.

CISC 105 – Topic 1 40


Placeholders and the
Newline Escape Sequence
printf(“The final GPA of student number %d is %f.\n”,student_num,
GPA);
Therefore, if the student_num variable was set
to
10 and the GPA variable was set to 3.03
Specifies to display student_num,
this printf function call would cause:
which is an integer.
The final GPA of student number 10 is 3.03.
Specifies to display GPA,
to be displayed on the screen and any
which is an floating-point number.
subsequent output to begin on the next line.
CISC 105 – Topic 1 41
The scanf Function
■ The C function for reading input from
the user is scanf.
scanf(“%d %f”,&student_num, &GPA);

format input
string list

function
arguments
CISC 105 – Topic 1 42
The Format String
■ The format string is the set of placeholders
which specify what type of data is being
input.
■ The same placeholders are used as for printf,
except for when inputting a floating-point
number. A float type still uses the “%f”,
however the double type uses the “%lf”
placeholder.

CISC 105 – Topic 1 43


The Input List
■ The variables to store the inputted data are
specified in the input list. They must be in
the same order as their corresponding
placeholders.
■ Notice that each variable name is preceded
by a “&”.
■ The “&” is an operator which means “the
address of”.
■ Therefore, “&student_num” tells the scanf
function to store what it reads from the user
at the memory address of student_num.
CISC 105 – Topic 1 44
Placeholders and
the Input List
scanf(“%d %f”,&student_num, &GPA);

This pair specifies to read


in an integer and store it
at the memory address of
student_num, thus setting
the student_num variable
to the inputted value.

CISC 105 – Topic 1 45


Placeholders and
the Input List
scanf(“%d %f”,&student_num, &GPA);

This pair specifies to read


in a single-precision floating
point number and store it
at the memory address of
GPA, thus setting the GPA
variable to the inputted
value.

CISC 105 – Topic 1 46


Placeholders and
the Input List
scanf(“%d %f”,&student_num, &GPA);

Therefore, if the input into this


scanf function call was:
9 3.560 <ENTER>
the student_num variable would be
set to 9 and the GPA variable would be
set to 3.560

CISC 105 – Topic 1 47


Review of printf and scanf
■ What is the displayed output when the
following code fragment is run and the
inputs are 8 and 12?
int x, y;

printf(“My name is”); My name is Phil Viscito.


printf(“ Phil Viscito”); Enter two integers> 8 12
printf(“\nEnter two integers> ”); Thanks! The answer is 22.
scanf(“%d%d”,&x, &y);
x = x + 2; Bye now!
y = x + y;
printf(“Thanks! The answer is %d.\nBye now!”,y);

CISC 105 – Topic 1 48


Customizing Integer Output
■ The “%d” placeholder, used to display an
integer variable, can be altered to format how
the number is displayed.
■ Instead of “%d”, use a “%Xd” where the X is
an integer that is the field width, the number
of digits to display.
■ For example, “%4d” displays four digits of the
result. The negative sign (for negative
integers) is also considered a digit here.
CISC 105 – Topic 1 49
Customizing Integer Output
■ When there are more places (the field
width) than digits to be displayed, the
output is right-justified.
■ When there are more digits than places,
the field width is ignored, and the entire
integer is displayed.

CISC 105 – Topic 1 50


Customizing Integer Output
■ As an example:
Value Placeholder Output
643 %1d 643
643 %4d 643
643 %5d 643
-643 %2d -643
-643 %6d -643
CISC 105 – Topic 1 51
Customizing
Floating-Point Output
■ Floating point output (float and double)
can be formatted in the same manner, using
“%X.Yf”).
■ Here, X is the total number of digits to display
(the field width) and Y is the number of digits
to display to the right of the decimal point.
■ The same rules for field width apply as for
integer formatting.
■ The specified number of decimal digits is
always displayed.
CISC 105 – Topic 1 52
Customizing
Floating-Point Output
■ As an example:
Value Placeholder Output
3.14159 %5.2f 3.14
3.14159 %3.2f 3.14
3.14159 %5.3f 3.142
0.1234 %4.2f 0.12
-0.006 %8.5f -0.00600
CISC 105 – Topic 1 53
Arithmetic Expressions
■ Arithmetic expressions are executable
statements that manipulate data.
■ Arithmetic expressions operate on both
integer (int) and floating-point (float and
double) numbers.
■ Arithmetic operators can operate on mixed
types (i.e. one int and one float). The
resulting type of such an expression is the
“highest” data type present.
CISC 105 – Topic 1 54
Resulting Data Types
■ The “highest” data type is always
considered to be a floating point
number, with double-precision floating
point numbers taking precedence over
single-precision floating point numbers.
int + int = int
int + float = float
int + double = double
float + double = double

CISC 105 – Topic 1 55


Arithmetic Expressions
■ All of the common arithmetic operators
are present in C:
■+ (addition)
■- (subtraction)
■* (multiplication)
■/ (division)
■% (modulus – or “remainder”)

CISC 105 – Topic 1 56


Note: Integer Division
■ If two integer values are divided, the
resulting data type is also an integer, as
previously described.
■ Therefore, only the integer portion of
the actual result will be the returned
result.
■ For example, 9 / 4 = 2
9 / 10 =0

CISC 105 – Topic 1 57


The Modulus Operator
■ The “%” operator is a modulus
operator, which also means the
remainder of the division.
■ For example,
9%3 =0
10 % 6 = 4
90 % 8 = 2

CISC 105 – Topic 1 58


Review of Basic
Arithmetic Expressions
■ What is the resulting output of this
program segment?
int x, y, z;
float a; x=4
a=4.5
x = 9 * 0.5;
a = 9 * 0.5; y=0
y = 15 % 15; z=1
z = 15 % 2;
printf(“x=%d\n, a=%f\n, y=%d\n, z=%d\n”,x,a,y,z)

CISC 105 – Topic 1 59


More Complex
Arithmetic Expressions
■ C evaluates arithmetic expressions in
the same order rules as normal
mathematics.
■ Parentheses take priority over everything
else.
■ Then, multiplication, division, and modulus
operations from left to right.
■ Then, addition and subtraction from left to
right.

CISC 105 – Topic 1 60


More Complex
Arithmetic Expressions
x2 + 2xy + 4y2 (x * x) + (2 * x * y) +
(4 * y * y)

a+b (a + b) / (c * c * 4 *
d)
--------
c2 * 4d
a * (4x % y2) a * (4 * x % (y * y))

x + y(x2 + y) x + y * (x * x + y)

CISC 105 – Topic 1 61


Review
■ What is the resulting output of this
program segment?
#define PI 3.14159

int x, y, z; x=5, y=10, z=4008


float a, b;
a=4008.14, b=4008.14159
x = 5;
y = 10;
z = x + (4 * y * y * y) + PI; Since x and y are both
a = x + (4 * y * y * y) + PI; integers, this evaluates
b = (x / y) + a;
to 0!
printf(“x=%d, y=%d, z=%d\na=%7.2f, b=%f\n”,x,y,z,a,b);
CISC 105 – Topic 1 62
Another Special Case:
Increment and Decrement
■ Incrementing (adding one) and
decrementing (subtracting one) are two
very common operations.
■ C has a special syntax for increment
and decrement operations that follows
this form:
x++; OR ++x; x--; OR --x;

Increment Decrement
CISC 105 – Topic 1 63
Another Special Case:
Increment and Decrement
■ Notice that the increment operator expression
x++ is the same as saying: x += 1;
■ So, why are there two forms of each operator?
■ The answer lies in when the increment (or
decrement) operation is actually performed.
■ This distinction only occurs when the ++ (or --)
operator is used on a variable in the same
expression in which the value of the variable is
used.

CISC 105 – Topic 1 64


Another Special Case:
Increment and Decrement
■ For example,
int x = 20, y; int x = 20, y;

y = x++; y = ++x;
printf(“x=%d, y=%d\ printf(“x=%d, y=%d\
n”,x,y); n”,x,y);

x=21, y=20 x=21, y=21

y = x; x += 1;
x += 1; y = x;
printf(“x=%d, y=%d\ printf(“x=%d, y=%d\
n”,x,y); n”,x,y);
CISC 105 – Topic 1 65
Another Special Case:
Increment and Decrement
■ The difference lies in when the expression
(x++ or ++x) gets evaluated in relation to
when the operator (++) gets performed.
■ The x++ expression is equal to the value of x
and the ++ operator is performed after the
evaluation is over.
■ The ++x expression indicates that the ++
operator is performed first (before ++x is
evaluated) and thus, is equal to the value of x
+ 1.
CISC 105 – Topic 1 66
Review
■ What is the output of the following
program fragment?
int x, y, z;

x = 5; x=7, y=10, z=55


y = 10;

z = x++ * y – 2;
z += ++x;

printf(“x=%d, y=%d, z=%d\n”,x,y,z);

CISC 105 – Topic 1 67


Topic 2A –
Library Functions and Casting
Casting
■ Although each of the functions above
take (and return) double data types,
they can be used with float data types.
■ This is done with a cast.
■ A cast is the conversion of one data
type to another data type.
■ This can be done explicitly or implicitly.

CISC 105 – Topic 1 69


Implicit Casting
■ When evaluating mixed type expressions, an
implicit cast is performed, as mixed type
expression cannot be directly evaluated.
■ For instance, in the code fragment:
float x = 1.0, y;
int z = 2;

y = x + z;

■ The variable z is casted to a float (2.0) in


order to add it to the float-type x.
CISC 105 – Topic 1 70
Review
■ What is the result of the following code
fragment:
int w, z, q;
float x = 4.0, y;

y = sqrt(x);
w = y; y=2.0, w=2, z=2, q=1
z = x – w;
q = sqrt(3);

printf(“y=%f,w=%d,z=%d,q=%d”,y,w,z,q);

CISC 105 – Topic 1 71


Explicit Casting
■ Casting can also be performed
explicitly. This is done with the
following form. What is the result of
the following code fragment?
int a=9, b=4;
float c,d; c=2.00, d=2.25
c = a/b;
d = (float)a / (float)b;

printf(“c=%.2f,d=%.2f”,c,d);
CISC 105 – Topic 1 72
Topic 3 – The General Form
of a C Program
The main Function Header
■ Thus, a general C program looks like:
Preprocessor directives

int main()
{

variable declarations

executable statements

return(0);
}

CISC 105 – Topic 1 74


Review (Problem #1)
■ Write a complete C program that asks
the user for a floating-point number,
multiplies the number by 4 * PI (with PI
set to 3.14159 in a constant macro) and
then outputs the result.

CISC 105 – Topic 1 75


Review (Problem
#include <stdio.h>
#1)
#define
■ WritePIa complete
3.14159 C program that asks
int the user for a floating-point number,
main()
{ multiplies the number by 4 * PI (with PI
float
set tonumber,
3.14159answer;
in a constant macro) and
then outputs the result.
printf(“Number?”);
scanf(“%f”,&number);
answer = number * 4 * PI;
printf(“The answer is:%f\n”,answer);
return (0);
}
CISC 105 – Topic 1 76
Topic 5 – Control Structures
The if statement
■ In order to use a condition to make a decision
about program control flow, C uses an if
statement.
■ The if statement first evaluates the specified
condition.
■ If the condition is true, the statement
immediately following the if statement
executes. If the condition is false, the
statement immediately following the if
statement is skipped.
CISC 105 – Topic 1 78
The if/else Statement
■ In addition, C supports the use of an else
statement.
■ This statement can follow the optional
statement (the one that may or may not
execute depending on the condition).
■ If there is an else statement, the statement
immediately following the else statement will
execute if the original condition (in the if
statement) is false.
CISC 105 – Topic 1 79
The if/else Statement
■ Therefore, if there is an else
statement, either the statement
immediately following the if statement
is run (if the condition is true) OR the
statement immediately following the
else statement is run (if the condition is
false).

CISC 105 – Topic 1 80


The if/else Statement
statement1;
if (condition)
statement2;
else
statement3;
statement4;

■ In this program fragment, statement1


executes. Then, either statement2 or
statement3 executes, depending on the
condition. Then, statement4 executes.
Note that only 3 statements execute.
CISC 105 – Topic 1 81
Compound Statements
■ Sometimes, we wish to perform more than
one thing as the result of an if statement.
■ In this case, we can make use of a compound
statement.
■ A compound statement is a group of C
language statements that run sequentially. A
compound statement is enclosed with curly
braces (“{” and “}”), in the same way a
function body is.
CISC 105 – Topic 1 82
Compound Statements
■ When used as the statement
immediately following an if or else
statement, a compound statement is
treated like one statement (all of the
statements enclosed by the braces are
run, sequentially.)

CISC 105 – Topic 1 83


Compound Statements
■ In this program fragment,
statement1;
statement1 executes. Then, if (condition)
{
either statement2 and statement2;
statement3 execute or }
statement3;

statement4 and statement5 else


{
execute, depending on the statement4;
statement5;
condition. Then, statement6 }
statement6;
executes. Note that only 4
statements execute.
CISC 105 – Topic 1 84
Cascading if/else Statements
■ We can also cascade if/else
statement1;
statements. Here, condition1 is first if (condition1)
evaluated. If it is true, statements 2 & {
statement2;
3 run and then statement7. If statement3;
condition1 is false and condition2 is }
else if(condition2)
true, statements 4 and 5 run and then {
statement 7. If both conditions are statement4;
false, statement 6 runs and then statement5;
}
statement 7. else
■ Note that if condition1 is true, statement6;
statement7;
condition2 is never evaluated!
CISC 105 – Topic 1 85
Conditions
■ So, now the structure of if/else statements
are known. So, how do we write the
conditions?
■ When an if statement is encountered, the
program will first evaluate the condition in the
if statement. Anything that evaluates to a
nonzero value is true. Anything that
evaluates to zero is false.

CISC 105 – Topic 1 86


Conditions
■ Thus, an if statement that was written
as:
if (x)
statement1;

would cause statement1 to run if x was


equal to any value other than zero. If
x was zero, statement1 would be
skipped.

CISC 105 – Topic 1 87


Relational and
Equality Operators
■ In order to write conditions effectively,
C provides a number of relational and
equality operators.
■ For these operators, if the condition
they specify is true, they evaluate to 1.
If the condition they specify is false,
they evaluate to 0.

CISC 105 – Topic 1 88


Operators
■ The following relational and equality
operators are used:
■ < less than
■ > greater than
■ <= less than or equal to
■ >= greater than or equal to
■ == equal to
■ != not equal to

CISC 105 – Topic 1 89


Conditions & Operators
■ Some examples of the use of these
operators include:
■ x <= 0
■ number > MAX_NUMBER_ALLOWED
■ male_or_female == ‘M’
■ num != flag_number
■ y < 12.0
■ q <= p

CISC 105 – Topic 1 90


A VERY Common Error
■ An assignment statement evaluates to
the value being assigned. For example,
x = 6;

evaluates to 6. So…what would happen


if we wrote
if (x = 6)
{

}

CISC 105 – Topic 1 91


A VERY Common Error
■ An assignment statement evaluates to
the value being assigned. For example,
First, 6 would be assigned to x!
xThis
= 6;overwrites whatever was previously
stored in x. Also, x=6 evaluates to 6.
evaluates to 6. So…what
As anything would
nonzero is true, happen
this condition
if we wrote is ALWAYS true.
if (x = 6) BOTTOM LINE:
{

Remember to use == for conditions!
}

CISC 105 – Topic 1 92


Compound Conditions
■ More than one condition can be
combined to create a compound
condition.
■ A logical operator is used to combine
conditions. These include:
■ && AND
■ || OR (shift-\)

CISC 105 – Topic 1 93


Logical AND (&&)
■ The logical AND operator works as
follows:
Condition 1 Condition 2 Overall Result
TRUE (nonzero) TRUE (nonzero) TRUE (1)
TRUE (nonzero) FALSE (0) FALSE (0)
FALSE (0) TRUE (nonzero) FALSE (0)
FALSE (0) FALSE (0) FALSE (0)
CISC 105 – Topic 1 94
Logical OR (||)
■ The logical OR operator works as
follows:
Condition 1 Condition 2 Overall Result
TRUE (nonzero) TRUE (nonzero) TRUE (1)
TRUE (nonzero) FALSE (0) TRUE (1)
FALSE (0) TRUE (nonzero) TRUE (1)
FALSE (0) FALSE (0) FALSE (0)
CISC 105 – Topic 1 95
Logical NOT (!)
■ The last logical operator is the NOT
operator. It behaves as follows:
Condition !(Condition)

TRUE (nonzero) FALSE (0)

FALSE (0) TRUE (1)

CISC 105 – Topic 1 96


Examples
■ Write a condition that is true if both x is
greater than 19.75 and number is equal
to 3 OR big_letter is not equal to ‘Q’.

(X > 19.75 && number == 3) || big_letter != ‘Q’

CISC 105 – Topic 1 97


The switch Statement
■ When one variable (type int or char
ONLY) is used to make a control decision,
where different statements are run if the
variable is equal to different values, the
switch statement can be used.
■ Note that this statement does not allow less
than, greater than, etc. ONLY the equality
operator (==) is used with a switch
statement.
■ The switch statement is composed of a
control variable and a series of case clauses.
CISC 105 – Topic 1 98
The switch Statement
switch(control variable)
{
case (value1):
. . .
. . .
■ The switch break;

statement takes case (value2):


. . .
this form: . . .
break;

default:
. . .
. . .
break;
}
CISC 105 – Topic 1 99
The switch Statement
switch(control variable)
■ When the switch {
statement is case (value1):
encountered, the . . .
control variable is . . .
break;
evaluated. Then, if
that evaluated value is case (value2):
equal to any of the . . .
values specified in a . . .
case clause, the break;
statements default:
immediately following . . .
the colon (“:”) begin to . . .
run. break;
}
CISC 105 – Topic 1 100
The switch Statement
switch(control variable)
{
■ These statements case (value1):
then continue to . . .
. . .
run until a break break;
statement is
encountered. case (value2):
. . .
Control then flows . . .
to the statement break;
immediately default:
following the . . .
closing brace (“}”). . . .
break;
}
CISC 105 – Topic 1 101
The switch Statement
switch(control variable)
{
■ It is important to case (value1):
remember that . . .
. . .
control will pass break;
into the next case case (value2):
clause if a break . . .
. . .
statement is not break;
encountered.
default:
. . .
. . .
break;
}
CISC 105 – Topic 1 102
The switch Statement
switch(control variable)
{
■ So, what happens if case (value1):
the control variable . . .
. . .
is not equal to any break;
of the values case (value2):
specified in the . . .
. . .
case clauses? break;
■ The default case default:
clause runs. . . .
. . .
break;
}
CISC 105 – Topic 1 103
switch Statement Example
statement1;
switch(x)
{ Which statements run
case (3):
statement2;
if:
statement3; x = 1?
case (27): x = 2?
case (1):
statement4;
x = 3?
case (2): x = 10?
statement5; x = 27?
break;
default:
statement6:
statement7:
break;
}
statement8;
CISC 105 – Topic 1 104
Topic 6 –
Repetition and Loops
The while Statement
■ In order to create loops in the C
language, the while statement can be
used. This statement follows the form:
while (condition)
{
statement1;
statement2;
. . .
}

CISC 105 – Topic 1 106


The while Statement
■ When the while statement is
first encountered, the
while (condition)
condition is evaluated. If it is {
true (nonzero), the loop body statement1;
executes sequentially. If the statement2;
. . .
condition is false, the loop }
body is skipped. Notice that
this behavior is exactly the
same as a simple if
statement.

CISC 105 – Topic 1 107


The while Statement
■ At the end of the loop body
(when the closing brace “}” is
while (condition)
encountered) the condition is {
evaluated again. If it is true, statement1;
the loop body begins to statement2;
. . .
execute again, beginning with }
the first statement in the body
(immediately following the
open brace “{”) and continuing
to the end sequentially.

CISC 105 – Topic 1 108


Counting Loops
and while Statements
■ As we have seen, counting loops have
three principle components when
created with a while statement:
■ Initialization – set the initial value of the
loop control variable (usually to zero)
■ Testing – Test the value of the loop
control variable according to the condition
■ Updating – Update the loop control
variable as the last statement in the loop

CISC 105 – Topic 1 109


A Common Loop Error
■ What happens if, when writing a
counting loop, the programmer does
not update the loop control variable?

The condition will always be true


(assuming it starts off as true). Thus,
the loop with execute forever. This
is referred to as an infinite loop.

CISC 105 – Topic 1 110


The for Statement
■ As we have seen, many loops have
three components in addition to the
loop body:
■ Initialization – set the initial value of the
loop control variable
■ Testing – Test the value of the loop
control variable according to the condition
■ Updating – Update the loop control
variable

CISC 105 – Topic 1 111


The for Statement
■ The for statement offers a designed
place for each of these three
components. It follows the form:
for (counter = 0;
counter <
high_value;
counter++)
{
statement1;
statement2;
. . .
}
CISC 105 – Topic 1 112
The for Statement
■ Thus, the for
statement consists of
an initialization, a for (counter = 0;
counter <
semicolon, the high_value;
counter++)
condition, a {
statement1;
semicolon, and the statement2;
an update }
. . .

statement.

CISC 105 – Topic 1 113


The for Statement
■ Notice that the update
statement does NOT
have a semicolon. for (counter = 0;
■ Also, the initialization counter <
high_value;
and update statements counter++)
{
can actually be statement1;
composed of more than statement2;
. . .
one statement. }

CISC 105 – Topic 1 114


The for Statement
■ If more than one
statement is to be
used for initialization for (counter = 0, x = 0;
counter <
or update, these high_value;
counter++, x += 2)
statements are {
statement1;
separated by statement2;
commas. }
. . .

CISC 105 – Topic 1 115


for / while Loop Equivalence
■ Notice that any for loop can be
rewritten into a while loop.
■ The for loop is simply a special case of
the while loop, with provisions for
initialization and updating build into the
loop statement itself.

CISC 105 – Topic 1 116


for / while Loop Equivalence
■ To convert from a for loop to a while
loop, simply move the initialization
statement(s) before the loop statement
and move the update statement(s)
inside the loop body.
■ We can rewrite the payroll example
using a for loop instead of a while
loop.
CISC 105 – Topic 1 117
The Payroll Example
with a for Loop
printf(“How many employees do you have?”);
scanf(“%d”,&number_employees);
total_pay = 0.0;
for (counter = 0; counter <
number_employees;
counter++)
{
printf(“Hours?”);
scanf(“%d”,&hours);
printf(“Pay rate?”);
scanf(“%lf”,&rate);
pay = hours * rate;
printf(“The pay is %f.\n”,pay);
total_pay += pay;
}
printf(“Total pay = %f.\n”,total_pay);
CISC 105 – Topic 1 118
The do-while Statement
■ Both of the loop statements we have seen
evaluate the condition before the first loop
iteration.
■ Sometimes, we wish to check the condition at
the end of the loop iteration, instead of at the
beginning of the loop iteration.
■ This has the effect of ALWAYS executing the
loop the first time, then testing the condition
at the end of the loop iteration.
CISC 105 – Topic 1 119
The do-while Statement
■ In order to create such loops, C offers
the do-while statement.
■ This loop follows the format:
do
{
statement1;
statement2;
. . .
} while
(condition);

CISC 105 – Topic 1 120


The do-while Statement
■ When the do statement
is first encountered, the
loop body begins to statement1;
execute immediately. do
{
■ When the loop body statement2;
statement3;
completes, the while . . .
statement is reached. } while
(condition);
■ The condition is then statement4;

evaluated.
CISC 105 – Topic 1 121
The do-while Statement

■ Notice that the


statement1;
while statement has do
{
a semicolon at the statement2;
end of the condition. statement3;
. . .
} while
(condition);
statement4;

CISC 105 – Topic 1 122


The do-while Statement
■ So…the do-while loop
statement is the same
as the while statement
statement1;
except the condition is do
tested at the end of the {
statement2;
loop iteration rather statement3;
than the beginning. . . .
} while
■ Thus, a do-while loop (condition);
ALWAYS executes at statement4;
least once.

CISC 105 – Topic 1 123


do-while and
while Comparison
■ Do the following loops do the same thing?
scanf(“%d”, &num); do {
while (num != SENTINEL) scanf(“%d”, &num);
{ if (num != SENTINEL)
/* do something {
with num */ /* do something
scanf(“%d”, &num); with num */
} }
} while (num != SENTINEL)

Loop
Yes,#1 Loop
the loops do the same #2
thing.
Is one better than the other? Why?
CISC 105 – Topic 1 124
Common Loop Errors
■ Find the error(s) in the following code:
#include <stdio.h>

/* This program asks for a number and displays


that
many lines of stars on the screen. */

int main()
{
int count, num_lines;
printf (“How many lines would you like?”);
scanf(“%d”,&num_lines);
for (count = 0; count <= num_lines; count++)
printf (“********************\n”);
return 0;
} CISC 105 – Topic 1 125
Common Loop Errors
■ Find the error(s) in the following code:
#include <stdio.h>
/* This program asks for numbers and keeps a running
sum. It terminates when –99 is entered. */
int main()
{
int sum, number;
do {
printf(“Enter a number (-99 to quit)>”);
scanf(“%d”,&number);
sum += number;
} while (number != -99);
printf (“The sum is %d.\n”,sum);
return 0;
}
CISC 105 – Topic 1 126

You might also like