+
CPS125
Week 2
2
How to Access a Memory
Location?
o
Either use the corresponding address
Or
o
Declare a variable and use the variable name
Variable
Specific memory location
Set aside for specific kind of data
Has a name for reference
Has an address for reference
2
+ scanf( ) function
Q) How to get the address of a variable?
A) By using the address operator (&), we can get the address.
e.g.
main( ){
int Var=5;
…
}
Var in this example represents the value of variable which is 5.
(from memory point of view, Var represents the content of the memory set aside
for
Var and that content again is 5)
&Var in this example represents the address of the variable which is 1002.
3
4
Address Of Var In Memory
1000
…
1001
…
1002
5
1003
…
1004
…
Var
+
Pointers
POINTERS IN C
6
Memory is a collection of storage locations.
Locations are numbered sequentially.
Each location has a unique address.
Address
…
…
1000
1001
1002
1003
1004
1005
…
…
Memory
+ /* PROGRAM # 45 */
/* DEMONSTRATES USE OF MEMORY STORAGE */
#include <stdio.h>
main( ){
int number;
int var;
int sum;
number = 55;
var = 25;
/* Add two integer numbers */
sum=number + var;
printf("sum is %d", sum);
}
Q) What does “int number;” do?
A) Compiler looks at the memory and tries to set aside enough storage (2
bytes for an integer for example) for a new variable that is called number.
This location can be anywhere in the memory that is actually available for
usage (i.e., is free).
7
Memory Map
Address
8
Memory
…
…
1000
55
number
25
var
80
sum
…
2000
…
3000
…
…
…
Memory Address of Variables
In this example:address 1000 and 1001 are set aside for number.(We may note
that knowing the address 1000 is enough since number is INTEGER and we
know int needs 2 bytes so knowing the address of first byte would be
sufficient.)
address 2000 and 2001 are set aside for var.
address 3000 and 3001 are set aside for sum.
+ Memory Location
So, there are 2 methods of accessing the memory locations
that holding the value of the variable number:
1)
We can use the name that we have picked up for that
location, i.e., number
2)
We can use the address of the location, i.e., 1000
We already know how to use number as the variable name
in a C program.
Pointers are needed if we want to use the address instead.
9
+
10
Address Operator
Q) How do we get hold of the address of a variable?
A) We can use the address operator.
&
EXAMPLE:
number
name of the variable
&number
address of the variable
is the address operator.
+ /* PROGRAM # 46 */
/* DEMONSTRATES USE OF ADDRESS OPERATOR*/
#include<stdio.h>
main( ){
int number = 55;
/* Display address of the variable in memory */
printf(" The address of the variable is: %d\n",&number);
/* Display value of the variable */
printf(" The value of the variable is: %d\n", number);
}
The address of the variable is: 1002
The value of the variable is: 55
11
+
Pointer Declaration in C
Q)
What does a pointer variable hold?
A)
Pointers are holding addresses.
Q)
Anything else we need to know?
A)
Immediately afterward, get the pointer to point to a variable.
Q)
How to declare a pointer?
A)
3 steps:
Pick up a name for the pointer variable
Put a * before the pointer name to indicate that this is a pointer variable not a regular variable
Indicate what type of data we find in that address
Q)
How to get the pointer to point to a variable?
A)
Assign the address of a variable to the pointer.
Make sure the data types are matching.
Q)
variable as well?
A)
Declare the pointer.
Any regular variable has address associate with it. Would it be true for pointer
Yes. Any pointer variable has also an address.
12
+
13
/* PROGRAM # 47 */
/* BASIC POINTER USE*/
#include <stdio.h>
main( ){
int number;
int *ptr;
/* declare a regular variable*/
/* declare a pointer variable*/
/* note: the pointer’s name is ptr, NOT *ptr
*/
number = 55;
/* assign a value to the regular variable */
ptr = &number;
/* assign an address to pointer variable */
/* by putting the address of the regular variable in a pointer variable, we get
the pointer to point to the variable */
}
+ Storage Space of Different types of variables
Address
Memory
…
…
1000
1001
1002
1003
number
55
1004
…
…
2000
2001
2002
2003
ptr
1002
14
+
15
Using the Pointer
Two new operators:
*
indirection operator
&
address operator
Passing Variables
with Pointers :
One possible use of the pointer is to Change the value of
variable pointed to by the pointer. For this we need to know
what does *ptr means?
One Good Application of Pointers:
Pointers can be used to pass more than one variable back from
a function.
+
/* PROGRAM # 48 */
/* PROPER USE OF POINTER*/
#include <stdio.h>
main( ){
int number;
/* Declare pointer */
int *ptr; number = 55;
/* Initialize ptr to point to number */
ptr = &number;
printf("Address stored in pointer is %d\n", ptr);
printf("Address of pointer is %d\n", &ptr);
printf("Value pointed to by the pointer is %d\n", *ptr);
printf("Value stored in the regular variable is %d\n", number);}
NOTE:
Things to remember when dealing with pointers:
ptr:
&ptr: gives the address of the pointer variable.
*ptr: gives the value stored at the memory location whose address is stored in the
pointer variable
contains the address stored in the pointer variable.
.
16
+ /* PROGRAM # 49 */
/* PASSING VARIABLES USING POINTERS*/
#include <stdio.h>
main( ){
/* Declare pointer ptr */
int *ptr;
int variable;
variable = 55;
/* Initialize ptr to point to variable */
ptr = &variable; /* remember we should get the pointer to point to a
variable as soon as we can */
printf("The value stored in variable right now is %d\n", variable);
*ptr = 77; /* change the content of the location pointed
to by the pointer variable, ptr */
printf("Notice that we changed the value stored in variable using the
pointer%d\n", variable);}
17
Passing Variables using Pointers (Change of Value of
+ the Variable )
Address
Memory
Adress
…
…
…
…
1000
1000
1001
1001
1002
1003
55
number
1002
1003
1004
1004
…
…
…
…
2000
2001
ptr
1002
Memory
77
2000
2001
2002
2002
2003
2003
number
ptr
1002
18
+
puts( ) function
similar
to printf( ) but just to use to print text (no
variable)
don’t
need to use \n since puts( ) automatically produce
one
must
include <stdio.h> in the program
20
Question
Q) What is the difference between the following 2
statements?
(num1 + num2)/2
AND
(num1 + num2)/2.0
21
Answer
A) This operation is division and num1 and num2 are
integer numbers. Therefore, in (num1 + num2)/2,
we are dividing an integer by a second integer and
as such the result would be another integer. The
average produced this way is incorrect.
(num1 + num2)/2.0, however, represents a case
where 2.0 is a float constant and the result of the
division would produce the correct float average.
22
Practice more Q
/* TO CALCULATE AVERAGE OF TWO INTEGER NUMBERS
*/
23
Practice! /* PROGRAM # 3 */
#include<stdio.h>
/* TO CALCULATE AVERAGE OF TWO INTEGER NUMBERS */
int main(void ){
int num1, num2;
float average;
/* Input two numbers */
puts(“Pls enter two integer numbers & we’ll average them for you”);
scanf(“%d %d”, &num1, &num2);
/* Calculate the average */
average=(num1 + num2)/2.0;
/* Display the average of two numbers and message Thanks you! */
printf(“The average is %f.\n”, average);
puts(“Thank You!”);
}
24
Practice! /* PROGRAM # 3 */
25
Type Casting
Good programming practice:
o
DO NOT MIX DATA TYPES
o
USE TYPE CASTING INSTEAD
Type casting:
Converting a variable to a particular type.
Done by using a unary cast operator ( )
General Synatx:
( type ) variable
e.g.,
int value
(float)value
26
Practice! /* PROGRAM # 5* /
/* TO CONVERT VARIABLE’S TYPE */
#include<stdio.h>
int main(void ){
int var;
/* Get a number */
printf(“Pls enter an integer number: “);
scanf(“%d”, &var);
/* Print the number as an integer */
printf(“The integer number that you entered is: %d.\n”, var);
/* Print the number as a float */
printf(“The integer number printed as a float is: %f.\n”, (float)var);
}
27
Practice! /* PROGRAM # 5* /
28
+
CPS125
+
30
Did
you finish your practice
from the previous slides????
Practice MORE! /* PROGRAM # 5* /
/* TO CONVERT VARIABLE’S TYPE */
#include<stdio.h>
int main(void ){
int var;
/* Get a number */
printf(“Pls enter an integer number: “);
scanf(“%d”, &var);
/* Print the number as an integer */
printf(“The integer number that you entered is: %d.\n”, var);
/* Print the number as a float */
printf(“The integer number printed as a float is: %f.\n”, (float)var);
}
31
Practice! /* PROGRAM # 5* /
32
+
CONDITIONAL STATEMENTS
RELATIONAL/EQUALITY OPERATORS
THE IF STATEMENT
LOGICAL OPERATIONS – AND, OR, NOT
PRECEDENCE FOR C OPERATORS, MATHEMATICAL, RELATIONAL,
LOGICAL
TYPE CASTING
C SWITCH
CONDITIONAL OPERATOR
34
Control Structures
35
Control structures combine individual instructions into a single logical unit
with one entry point at the top and one exit point at the bottom.
3 kinds of control structures:
Sequence (default control structure)
Selection (branches)
Repetition (loops)
Conditions
A condition is an expression that is either
true or false.
Ex: CPS125_Grade=98;
CPS125_Grade < 0 will be false
CPS125_Grade >90 will be true
Comparison (relational) operators are:
< > <= >= == !=
36
37
Relational Operations
Relationship between 2 variables, expressions
Returns a numerical value depending on the result
The value returned for TRUE is 1, 0 otherwise
Relational Operators in C
Symbol
Purpose
>
Greater than
>=
Greater than or equal to
<
Less than
<=
Less than or equal to
38
Equality Operations
Equality between 2 variables, expressions
The value returned for TURE is 1, 0 otherwise
Equity Operators in C
Symbol
Purpose
==
Equal to
!=
Not equal to
Common Mistakes When Writing a C
Program
Missing #include…
Missing variable declaration
Wrong variable declaration
Missing semicolon
Incorrect assignment
Using the name of the variable instead of its address
Incorrect nested if
Wrong looping condition
Misusing pointers
Missing Braces
Using incorrect format specifier
39
Note on = and ==
=
denotes assignment
result of operation in right hand side
is assigned to the variable mentioned in
left hand side.
x = 5;
/* returns 5 to x*/
==
denoted equal to
is relational operators
returns either 1 or 0.
x == 6; /* returns 0 */
40
41
Logical Operators
A logical expression contains one or more comparison and/or
logical operators.
The logical operators are:
&&: the and operator, true only when all operands are true.
||: the or operator, false only when all operands are false.
!: the not operator, false when the operand is true, true when the
operand is false.
42
Logical Operations – AND, OR, NOT
Logical AND
(&&)
( expression1 ) && ( expression2 )
This operation is TRUE only if expression1 is TRUE and expression2 is TRUE.
Works based on the AND truth table as follows:
Logical AND Truth Table
Expression1
Expression2
AND
0
0
0
0
1
0
1
0
0
1
1
1
43
Logical OR Operation
Logical OR
(||)
(expression1) || (expression2)
This operation is FALSE only if expression1 is FALSE and expression2 is FALSE.
Works based on the OR truth table as follows:
Logical OR Truth Table
Expression1
Expression2
OR
0
0
0
0
1
1
1
0
1
1
1
1
44
Logical NOT Operation
Logical NOT
(!)
! (expression1)
This operation will negate the logical value of the expression.
Works based on the NOT truth table as follows:
Logical NOT Truth Table
Expression1
NOT
0
1
1
0
Precedence C
Operators/Mathematical/Relational, Logical
High
Operation
!
Logical Not
*, /
Multiplication and Division
+, -
Addition and Subtraction
<, <=, >=, >
==, !=
Low
Purpose
Less, Less or Equal, Greater
or Equal, Greater
Equal, Not Equal
&&
Logical AND
||
Logical OR
45
+ Expressions
-Identify variables
You could have A+-Z%B if they are non zero and integer.
You could not have the expression :ab-cd+3bx
After each operation we must have an operand: x+xy-z
Look at the ( )well. A+(b+c)-(a-d)
Do not use reserved words: void ,char.
You could use soft rules: A standard identifier is a name used by C
but is not a reserved word. printf, scanf are examples of standard
identifiers.
Be careful we must use functions in C for math .
46
Fast evaluation of logical expressions
• The trick is to divide the expression in sub expressions between the || and
evaluate the easiest first. As soon as you find a TRUE, the whole thing is true.
When there is no || operator. Divide the expression in parts between
the && operators. If one part is false, the expression is false.
NOTE:
0 means FALSE.
1 means TRUE.
ANY NONZERO VALUE IS TREATED AS TRUE.
47
+ Expressions
-x- y*z……..-x then y*z then –x-result of the second step.
(x<y || x<z) && x>0.0 …first &&
You can also use parentheses to clarify the meaning of the expression.
If x,min,max are type double ,the C compiler interprets the expression
x+y<min+max correctly as: (x+y)<(min+max)
48
English Conditions as C Expressions
49
English Condition
Logical Expression
Evaluation
X and Y are greater
than z
X> z && Y>z
1 && 1 is 1 (true)
X is equal to 1.0 or 3.0
X==1.0 || X== 3.0
0 || 1 is 1 (true)
x is in the range z to y,
inclusive
z<=x && x<= y
1 && 1 is 1 (true)
x is outside the range
z to y
!(z<=x && x<= y)
z>x || x> y
!(1 && 1) is 0 (false)
0 || 0 is 0 (false)
Comparing characters
•
'9' >'0' ?
'a' < 'e' ?
'B' <= 'A' ?
'Z' == 'z' ?
Is a letter lower-case?
letter >= 'a' && letter <= 'z'
Does the variable ch contains a letter?
(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
50
Character Comparisons
51
Expression
Value
‘9’> ‘0’
1 (true)
‘a’< ‘e’
1 (true)
‘B’<= ‘A’
0(false)
‘Z’== ‘z’
0(false)
‘a’<= ‘A’
System dependent
‘a’<= ch && ch <= ‘z’
1 (true) if ch is a lowercase letter
+
+ Logical Assignments
Assum that a value 1 for senior_citizen indicates that the person is a
senior citizen (65 years old or over).you can use the assignment
statement
senior_citizen =1; /*set senior status*/
To set senior_citizen to true.
A more likely scenario is to set the value of senior_citizen based on the
value scanned into age.
scanf(“%d”,&age); /*read the person’s age*/
senior_citizen=(age>=65); /*set senior status*/
In the assignment above , the condition in parentheses evaluates first. its
value is 1 (true) if the value scanned into age is 65 or greater.
Consequently, the value of senior_citizen is true when age satisfies the
condition and false otherwise.
53
+ Logical Assignments
The logical operators &&,||,and ! Can be applied to senior_citizen.
The expression ! senior_citizen is 1 (true) if the value of age is less
than 65.
senior_citizen &&gender==‘M’
Is 1(true )if senior_citizen is 1(true)and the character in gender is
M.
The statement below assigns the value 1(true) to even (type int) if n
is an even number:
even= (n%2==0)
Because all even numbers are divisible by 2,the remainder of n
divided by 2 (n%2 in C)is when n is an even number.
The expression in parentheses compare the remainder to 0,so its
value is 1 (true) when the remainder is 0 and its value is 0(false)
when the remainder is nonzero.
54
Math Formula….C Expression
Mathematical Formula
C Expression
b2 - 4ac
b*b – 4*a*c
a+ b- c
a + b -c
a+ b/ c+d
(a+ b) /(c+ d)
1/1+ x2
1/(1+x*x)
ax-(b+c)
a* -(b+c)
55
Condition complements
The opposite (or complement) of (x == 0) is !(x==0) or (x != 0).
The opposite of (x > 3) is !(x > 3) or (x <=3).
The opposite of (a == 10 && b > 5) is !(a ==10 && b > 5) or (a != 10 || b <=5)
De Morgan's Theorem:
The complement of exp1 && exp2 is comp_exp1||comp_exp2.
The complement of exp1||exp2 is comp_exp1 && comp_exp2.
56
The if Statement
o
How to use if statement for Decision-making capabilities
o
How to use relational operators
General Syntax:
if
(condition(s)){
/* body of if statement appears here!*/
}
Description:
If the condition or conditions are true then the body of the if statement is executed.
Note: Never put a ; after the condition.
57
Simplest form of if statement
o
body of if only includes ONE statement
o
don’t need braces, { }, to mark the body of the if. However, we can use them if
we want.
o
Don’t forget the semicolon at the end of the single statement.
if
(condition)
statement1;
statement2;
Description:
o
Conditional statement.
o
If the condition is TRUE then statement1 is executed.
o
If the condition is FALSE then statement1 is not executed.
o
Statement2 is NOT part of the IF statement and will always be executed
regardless of the status of the condition.
58
/* PROGRAM #7 */
/* USE OF IF STATEMENT */
#include <stdio.h>
main( ){
float MyGPA;
float MinGPA=2.0;
/* Input the GPA */
printf("Pls enter your GPA: ");
scanf("%f",&MyGPA);
/* Test the value of GPA and print the result */
if (MyGPA > MinGPA)
1st printf
printf("Your status might be clear.\n");
printf("Your GPA is %f.\n", MyGPA);
}
2nd printf
59
Execute1:
60
Execute2:
Note:
The body of the if is not marked by braces, therefore, we assume that it
contains only one statement that is the 1st printf statement in this example,
and the 2nd printf statement is actually outside the if body.
61
IF With A Compound Statement
o
Two/more statements are enclosed within braces { }.
o
Body of if includes more than one statement
o
Must use braces, { }, to mark the body of the if.
General Syntax:
if (condition(s)){
statement_1;
statement_2;
…
}
statement_N;
Description:
o
Conditional statement.
o
If the condition is TRUE then all the statements within the barces are executed.
o
Otherwise those statements are not being executed.
o
Statement_N is NOT part of the IF statement and will always be executed regardless of
the status of the condition.
62
+
IF … ELSE …
o
Very similar to the IF statement seen before.
o
Enhances the decision-making capability.
General Syntax:
if
(condition)
statement1;
else
statement2;
o
if the condition is TRUE then statement1 is executed.
o
Otherwise statement2 is executed.
NOTE:
if and else are C keywords, then is not.
63
+
/* Even vs. Odd */
#include <stdio.h>
int main (void) {
int number, even;
/* ask user for number */
printf ("Enter an integer number: ");
scanf ("%d", &number);
/* determine if number is even and put in variable */
even = (number % 2 == 0);
/* display report */
if (even)
printf ("%d is an even number.\n", number);
else
printf ("%d is an odd number. \n", number);
return (0);
}
64
/* PROGRAM #8 */
65
/* COMPOUND STATEMENT */
/* are you getting A+ in CPS125? */
#include <stdio.h>
/* need <stdlib.h> for exit( ), see Appendix */
#include <stdlib.h>
main( ){
float Grade125, GPA;
printf("Please enter your grade in CPS125: "); /* Input the grade */
scanf("%f", &Grade125);
/* Test if the grade is A+ and print the result */
if (Grade125 >= 90.0){
printf("You’re getting A+ in this course!\n");
/* Input the GPA */
printf("Please enter your GPA: ");
scanf("%f", &GPA);
printf("Your GPA is %f & you’re getting A+ in this course!\n",GPA); }
exit(0);
}
Result1:
Note on exit(0):
Is used to return the control to the OS.
66
What else…????complete the
answer…
67
Result2:
68
+
+
Practice! /* PROGRAM #9*/
/* PROGRAM TO CALCULATE COURSE MARKS */
#include <stdio.h>
#define MidTermWeight 0.30
#define ExamWeight 0.50
#define LabWeight 0.20
main( ){
70
float MidTerm, Exam, Lab; float WrittenWork, LabWork, Grade;
printf("Please enter your mid-term mark: ");
scanf("%f", &MidTerm);
printf("Please enter your exam mark: ");
scanf("%f", &Exam);
printf("Please enter your lab mark: ");
scanf("%f", &Lab);
WrittenWork = MidTerm * MidTermWeight + Exam * ExamWeight;
LabWork = Lab * LabWeight;
Grade = WrittenWork + LabWork;
if (Grade >= 90)
/* Input the mid-term, exam and lab mark */
/* Calculate the grade, test if the grade is A+ and print the result */
printf("Definitely A+.\n");
printf("Either B or C or D or even F!.\n");}
else
© Copyright 2026 Paperzz