0% found this document useful (0 votes)
32 views51 pages

Lecture 3-11327

Uploaded by

elkinaniosman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views51 pages

Lecture 3-11327

Uploaded by

elkinaniosman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

CSE121: Computer Programming (2)

)2( ‫ برمجة الحاسب‬:121 ‫هحس‬


1st Year
Computer and Systems Engineering &
Power and Electrical Machines Engineering

Zagazig University

Fall 2023
Lecture #3
Dr. Ahmed Amer Shahin
Dept. of Computer & Systems Engineering

These slides are adapted from the slides accompanying the text “C How to Program, 8/e,” https://deitel.com/c-how-to-program-8-e/
Copyright Deitel 2016
Announcements
• A New Team is created in Microsoft Teams:
– For communication, discussions, and
announcements.
• Faculty Platform:
– Continuously updated with Lectures, Tutorials,
and Labs
• Tutorials/Practical Sessions:
– Follow the schedule announced on Teams
Outline
• A C Program to compare two numbers
• Relational and Equality Operators
• Logical Operators
• Structured Program Development in C
– Algorithm, Pseudocode, and Flowchart
– Control Structures
• The selection statements (if, if…else, switch)
• Common Errors

3
Lecture Map

4
A C PROGRAM TO COMPARE TWO
NUMBERS
A C Program to Compare Two Numbers

• A program that uses six if statements to


compare two numbers entered by the user.
• If the condition in any of these if statements
is true, the printf statement associated
with that if executes.

© 2016 Pearson Education, Ltd. All rights reserved. 6


© 2016 Pearson Education, Ltd. All rights reserved. 7
© 2016 Pearson Education, Ltd. All rights reserved. 8
© 2016 Pearson Education, Ltd. All rights reserved. 9
RELATIONAL AND EQUALITY
OPERATORS
Relational and Equality Operators

These operators are binary operators, and the result from any
expression that contains a relational or equality operators is
either 0 (false) or 1 (true)
© 2016 Pearson Education, Ltd. All rights reserved. 11
Relational and Equality Operators
#include <stdio.h>

int main()
{
int a = 4, b = 9;

printf("a > b gives a value of %d\n", a > b);


printf("a < b gives a value of %d\n", a < b);

return 0;
}

a > b gives a value of 0


a < b gives a value of 1
12
Relational and Equality Operators

• Conditions in if statements are formed by


using the equality operators and relational
operators
• If the condition is true (i.e., the condition is
met) the statement in the body of the if
statement is executed.
• If the condition is false (i.e., the condition
isn’t met) the body statement is not
executed.

© 2016 Pearson Education, Ltd. All rights reserved. 13


Relational and Equality Operators

• Back to the program that compares two


numbers
– The if statement

if ( num1 == num2 ) {
printf( "%d is equal to %d\n", num1, num2 );
}

– compares the values of variables num1 and


num2 to test for equality.
© 2016 Pearson Education, Ltd. All rights reserved. 14
Relational and Equality Operators

• A left brace, {, begins the body of each if


statement
• A corresponding right brace, }, ends each if
statement’s body
• Any number of statements can be placed in the
body of an if statement.
• If the body contains one statement only, the
braces {} could be omitted.
• Indenting the body of each if statement
enhances program readability.

© 2016 Pearson Education, Ltd. All rights reserved. 15


LOGICAL OPERATORS

16
Logical Operators

• C provides logical operators that may be


used to form more complex conditions by
combining simple conditions.
• The logical operators are
&& (logical AND)
|| (logical OR)
! (logical NOT)

© 2016 Pearson Education, Ltd. All rights reserved. 17


Logical AND (&&) Operator
• Suppose we wish to ensure that two conditions are
both true before we choose a certain path of
execution.
• In this case, we can use the logical operator && as
follows:
if (gender == 1 && age >= 65)
++seniorFemales;
• This if statement contains two simple conditions.
– The condition gender == 1 might be evaluated, for
example, to determine if a person is a female.
– The condition age >= 65 is evaluated to determine
whether a person is a senior citizen.

© 2016 Pearson Education, Ltd. All rights reserved. 18


Logical AND (&&) Operator

• The if statement then considers the


combined condition
gender == 1 && age >= 65
• Which is true if and only if both of the simple
conditions are true.
• Finally, if this combined condition is true,
then the count of seniorFemales is
incremented by 1.

© 2016 Pearson Education, Ltd. All rights reserved. 19


Logical OR (||) Operator
• Suppose we wish to ensure at some point in a
program that either or both of two conditions are
true before we choose a certain path of execution.
• In this case, we use the || operator as in the following
program segment

if (semesterAverage >= 90 || finalExam >= 90)


printf("Student grade is A");

– The condition semesterAverage >= 90 is


evaluated to determine whether the student deserves
an “A” in the course because of a solid performance
throughout the semester.
© 2016 Pearson Education, Ltd. All rights reserved. 20
Logical OR (||) Operator
– The condition finalExam>=90 is evaluated to
determine whether the student deserves an “A” in
the course because of an outstanding performance
on the final exam.
• The if statement then considers the combined
condition
semesterAverage>= 90|| finalExam>= 90
• and awards the student an “A” if either or both
of the simple conditions are true.
• The message “Student grade is A” is not printed
only when both of the simple conditions are
false (zero).

© 2016 Pearson Education, Ltd. All rights reserved. 21


Logical Negation (!) Operator
• C provides ! (logical negation) to enable you to
“reverse” the meaning of a condition.
• The logical negation operator has only a single
condition as an operand (and is therefore a unary
operator).
• Placed before a condition when we’re interested in
choosing a path of execution if the original condition
(without the logical negation operator) is false, such
as in the following program segment:

if (!(grade == undefinedValue))
printf("The next grade is %f\n", grade);

© 2016 Pearson Education, Ltd. All rights reserved. 22


Logical Negation (!) Operator
• The parentheses around the condition grade ==
undefinedValue are needed because the logical
negation operator has a higher precedence than the
equality operator.
• In most cases, you can avoid using logical negation
by expressing the condition differently with an
appropriate relational operator.
• For example, the preceding statement may also be
written as follows:

if (grade != undefinedValue)
printf("The next grade is %f\n", grade);

© 2016 Pearson Education, Ltd. All rights reserved. 23


Short-circuit Evaluation
• The && operator has a higher precedence than ||.
• Both operators associate from left to right.
• An expression containing && or || operators is
evaluated only until truth or falsehood is known.
– Thus, evaluation of the condition
gender == 1 && age >= 65
– will stop if gender is not equal to 1 (i.e., the entire
expression is false), and continue if gender is equal to 1
(i.e., the entire expression could still be true if age >=
65).
• This performance feature for the evaluation of
logical AND and logical OR expressions is called
short-circuit evaluation.
© 2016 Pearson Education, Ltd. All rights reserved. 24
Summary of Operator Precedence and
Associativity

The operators are shown from top to bottom in


decreasing order of precedence.
© 2016 Pearson Education, Ltd. All rights reserved. 25
STRUCTURED PROGRAM
DEVELOPMENT IN C

26
Algorithm, Pseudocode, and Flowchart

• Before writing a program to solve a particular


problem, we must have a thorough
understanding of the problem and a carefully
planned solution approach.
• A procedure for solving a problem in terms of
– the actions to be executed, and
– the order in which these actions are to be executed
• is called an algorithm, which could be described
using a pseudocode or a flowchart
© 2016 Pearson Education, Ltd. All rights reserved. 27
Algorithm, Pseudocode, and Flowchart

• Pseudocode is an artificial and informal


language that helps you develop algorithms.
– Pseudocode is similar to everyday English; it’s
convenient and user friendly although it’s not an
actual computer programming language.
• A flowchart is a graphical representation of an
algorithm or of a portion of an algorithm.
– Flowcharts are drawn using certain special-purpose
symbols such as rectangles, diamonds, rounded
rectangles, and small circles; these symbols are
connected by arrows called flowlines.
© 2016 Pearson Education, Ltd. All rights reserved. 28
Control Structures

• Normally, statements in a program are


executed one after the other in the order in
which they’re written.
– This is called sequential execution.
• Various C statements we’ll soon discuss
enable you to specify that the next
statement to be executed may be other
than the next one in sequence.
– This is called transfer of control.

© 2016 Pearson Education, Ltd. All rights reserved. 29


Control Structures

• Research had demonstrated that all


programs could be written in terms of only
three control structures,
– the sequence structure,
– the selection structure, and
– the iteration structure.

© 2016 Pearson Education, Ltd. All rights reserved. 30


The sequence structure

• The sequence structure is simple—unless


directed otherwise, the computer executes
C statements one after the other in the
order in which they’re written.

© 2016 Pearson Education, Ltd. All rights reserved. 31


The Selection structure

• C provides three types of selection structures in


the form of statements.
– The if selection statement either selects
(performs) an action if a condition is true or skips
the action if the condition is false.
– The if…else selection statement performs an
action if a condition is true and performs a different
action if the condition is false.
– The switch selection statement performs one of
many different actions depending on the value of
an expression.

© 2016 Pearson Education, Ltd. All rights reserved. 32


The Iteration structure

• C provides three types of iteration structures


in the form of statements, namely
– while
– do…while
– for

© 2016 Pearson Education, Ltd. All rights reserved. 33


THE SELECTION STATEMENTS

34
The if Selection Statement
• The if statement is called a single-selection
statement because it selects or ignores a single
action.
• For example, suppose the passing grade on an exam
is 60.
– The pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
– The corresponding C Code could be
if (grade >= 60)
{
printf("Passed\n");
}
A flowchart for the statement
© 2016 Pearson Education, Ltd. All rights reserved. 35
The if…else Selection Statement
• The if…else statement is called a double-selection statement because
it allows you to specify that different actions are to be performed when
the condition is true and when it’s false.
• For example.
– The pseudocode statement
If student’s grade is greater than or equal to 60
Print “Passed”
else
Print “Failed”
– The corresponding C Code could be
if (grade >= 60)
{
printf("Passed\n");
}
else
{
printf("Failed\n");
}
A flowchart for the statement

© 2016 Pearson Education, Ltd. All rights reserved. 36


The Conditional Operator (?:)

• Closely related to the if…else statement.


Condition? value if true : value if false
• The conditional operator is C’s only ternary
operator—it takes three operands.
– The first operand is a condition.
– The second operand is the value for the entire
conditional expression if the condition is true
– The third operand is the value for the entire
conditional expression if the condition is false.
• These together with the conditional operator
form a conditional expression.

© 2016 Pearson Education, Ltd. All rights reserved. 37


The Conditional Operator (?:)
• For example, the statement

printf( grade >= 60 ? "Passed" : "Failed" );

• Has the same effect as the if…else statement.


if (grade >= 60)
{
printf("Passed\n");
}
else
{
printf("Failed\n");
}

© 2016 Pearson Education, Ltd. All rights reserved. 38


Nested if...else Statements
Pseudocode to print Grade Corresponding C code
If student’s grade is greater than or equal to 90 if (grade >= 90)
Print “A” puts("A");
else else if (grade >= 80)
If student’s grade is greater than or equal to puts("B");
80 Print “B”
else if (grade >= 70)
else
If student’s grade is greater than or equal to
puts("C");
70 Print “C” else if (grade >= 60)
else puts("D");
If student’s grade is greater than or equal to else
60 Print “D” puts("F");
else
Print “F”

© 2016 Pearson Education, Ltd. All rights reserved. 39


Test Your Understanding
What is the output here? What about here?
#include <stdio.h> #include <stdio.h>

int main(void) int main(void)


{ {
int n = 9, b = 7; int n = 9, b = 7;
if ((b < 6) ? n : n - n) if ((n == b) ? n - n : n)
{ {
printf("1st selected\n"); printf("1st selected\n");
} }
else else if ((b < 6) ? n : n - n)
{ {
printf("2nd selected\n"); printf("2nd selected\n");
} }
} }

2nd selected 1st selected

40
switch Multiple-Selection Statement

• The switch statement is called a multiple-


selection statement because it selects among
many different actions.
– For example, a series of decisions in which a variable
or expression is tested separately for each of the
constant integral values it may assume, and
different actions are taken.
• The switch statement consists of a series of
case labels, an optional default case and
statements to execute for each case.

© 2016 Pearson Education, Ltd. All rights reserved. 41


switch Multiple-Selection Statement
#include <stdio.h> #include <stdio.h>

int main(void)
int main(void) {
int count = 50;
{
switch (count)
int count = 50; {
case 90:
if (count == 90)
puts("****");
puts("****"); break;
else if (count == 80) case 80:
puts("***");
puts("***"); break;
else default:
puts("**");
puts("**");
break;
} }
}

© 2016 Pearson Education, Ltd. All rights reserved. 42


switch Multiple-Selection Statement
• Keyword switch is followed by a constant integral
expression in parentheses.
– This is called the controlling expression.
• The value of this expression is compared with each of
the case labels.
• If a match occurs, the statements for that case are
executed.
• The break statement causes program control to
continue with the first statement after the switch
statement.
– The break statement is used because the cases in a switch
statement would otherwise run together.
• If no match occurs, the default case is executed.

© 2016 Pearson Education, Ltd. All rights reserved. 43


COMMON ERRORS

44
Common Errors

• A syntax error is caught by the compiler.


int i; = 2;
• A logic error has its effect at execution time.
a = a * 2; //Getting the square of a
• A fatal logic error causes a program to fail
and terminate prematurely.
int *p = 0;
printf("%d", *p);

© 2016 Pearson Education, Ltd. All rights reserved. 45


Common Errors

• A nonfatal logic error allows a program to


continue executing but to produce incorrect
results.
• Forgetting a break statement when one is
needed in a switch statement is a logic
error

© 2016 Pearson Education, Ltd. All rights reserved. 46


Common Errors

• It possible to have no statement at all, i.e.,


the empty statement.
– The empty statement is represented by placing a
semicolon (;) where a statement would normally
be.
– This can cause a logic error as below
if (count < 100);
printf("More to process\n");

© 2016 Pearson Education, Ltd. All rights reserved. 47


Confusing Equality (==) and Assignment (=)
Operators
• There’s one type of error that C programmers, no
matter how experienced, tend to make so frequently
– That error is accidentally swapping the operators == (equality)
and = (assignment)
• The Equality (==) and Assignment (=) Operators have
different meanings in C
– Equality (==) Operator check if the both sides of the operator
are equal and returns either 1 (true) or 0 (false).
– Assignment (=) Operator assigns the value of the right-hand
side to the variable in the left-hand side.
• Assignments in C produce a value, namely the value that’s assigned
to the variable on the left side of the assignment operator.
var1 = var2 = var3 = 6; // all of them assigned a value of 6

© 2016 Pearson Education, Ltd. All rights reserved. 48


Confusing Equality (==) and Assignment (=)
Operators
• For example, suppose we intend to write
if (payCode == 4)
printf("%s", "You get a bonus!");
• but we accidentally write
if (payCode = 4)
printf("%s", "You get a bonus!");
• The first if statement properly awards a bonus
to the person whose paycode is equal to 4.

© 2016 Pearson Education, Ltd. All rights reserved. 49


Confusing Equality (==) and Assignment (=)
Operators
• The second if statement—the one with the error—
evaluates the assignment expression in the if
condition.
– This expression is a simple assignment whose value is
the constant 4.
• Because any nonzero value is interpreted as “true,”
– the condition in this if statement is always true,
– and not only is the value of payCode inadvertantly set to
4,
– but the person always receives a bonus regardless of
what the actual paycode is!

© 2016 Pearson Education, Ltd. All rights reserved. 50


END OF LECTURE

51

You might also like